v1.31.0
conocimientotesting-patternstemplates/1240 B

TestBase.cs.template

Fichero que /hv:testing-patterns usa o materializa en el proyecto. Se muestra tal cual está en el plugin.

testing-patternsskill
templatescarpeta
1240 Btamaño
2026-10-06último cambio del pack
// TEMPLATE: TestBase | Skill: testing-patterns
// Base class for unit tests with Moq + FluentAssertions
// Placeholders: {{ProjectNamespace}}

using FluentAssertions;
using Moq;
using Moq.AutoMock;
using Xunit;

namespace {{ProjectNamespace}}.Tests.Unit;

public abstract class TestBase<TSut> where TSut : class
{
    protected readonly AutoMocker Mocker = new();
    protected TSut Sut => Mocker.CreateInstance<TSut>();

    protected Mock<T> GetMock<T>() where T : class => Mocker.GetMock<T>();

    protected void SetupReturn<T, TResult>(
        System.Linq.Expressions.Expression<Func<T, Task<TResult>>> expression,
        TResult result) where T : class
    {
        Mocker.GetMock<T>().Setup(expression).ReturnsAsync(result);
    }
}

// EJEMPLO:
// public class ScholarshipServiceTests : TestBase<ScholarshipService>
// {
//     [Fact]
//     public async Task GetById_ReturnsScholarship()
//     {
//         var scholarship = new Scholarship { Id = 1, Name = "Test" };
//         SetupReturn<IScholarshipRepository, Scholarship?>(r => r.GetByIdAsync(1, default), scholarship);
//         var result = await Sut.GetByIdAsync(1);
//         result.Should().NotBeNull();
//         result!.Name.Should().Be("Test");
//     }
// }

← Volver a la ficha de testing-patterns