如何正确模拟扩展方法与泛型在xUnit?



所以我试图模仿我的一个服务,这里是真实的代码:

public class PhaseService : IPhaseService
{
private readonly IRepository<Phase> _phaseRepository;
private readonly IMapper _mapper;
private readonly HrbContext _context;
public PhaseService(IRepository<Phase> phaseRepository, IMapper mapper, HrbContext context)
{
_phaseRepository = phaseRepository;
_mapper = mapper;
_context = context;
}
public async Task<PhaseDto> GetAsync(Guid id)
{
var result = await _phaseRepository.GetActiveAsync(id);
return _mapper.Map<PhaseDto>(result);
}
}

它使用一个扩展方法,在这里:

namespace HRB_Server.Application.Extensions
{
public static class RepositoryExtensions
{
/// <summary>
/// Returns the entity to which the given id is a match (no navigation properties loaded). Throws exceptions if the entity is not found or if is not active.
/// </summary>
public static async Task<T> GetActiveAsync<T>(this IRepository<T> repo, Guid id)
where T : BaseEntity
{
T entity = await repo.GetAsync(id);
if (entity == null)
{
throw new EntityNotFoundException(typeof(T), id);
}
if (!entity.IsActive)
{
throw new EntityNotActiveException(typeof(T), id);
}
return entity;
}
}

下面是我的xUnit测试:

namespace HRB_Server.Tests.Services
{
public class PhaseServiceTest
{
private readonly Mock<IRepository<Phase>> _repository;
private readonly Mock<IMapper> _mapper;
private readonly Mock<HrbContext> _context;
public PhaseServiceTest()
{
_repository = new Mock<IRepository<Phase>>();
//_mapper = new Mock<IMapper>();
_mapper = null;
//_context = new Mock<HrbContext>(new DbContextOptions<HrbContext>(), new HttpContextAccessor());
_context = null;
}
[Fact]
public void GetPhase_ActivePhaseObject_PhaseShouldExist()
{
// Arrange
var newGuid = Guid.NewGuid();
var phase = GetSamplePhase(newGuid);
_repository.Setup(x => RepositoryExtensions.GetActiveAsync<Phase>(_repository, It.IsAny<Guid>()))
.Returns(GetSamplePhase(newGuid));
var phaseService = new PhaseService(_repository.Object, _mapper.Object, _context.Object);
// Act
var result = phaseService.GetAsync(newGuid);
// Assert (expected, actual)
Assert.Equal(phase.Result.Id, newGuid);
}
}

我得到的错误是在_repository的设置:

repository.Setup(x => RepositoryExtensions.GetActiveAsync<Phase>(_repository, It.IsAny<Guid>()))
.Returns(GetSamplePhase(newGuid));  

它说它不能将模拟存储库转换为真实的存储库,但是我不应该在这里使用模拟存储库吗?

我想要实现的是测试我的REAL服务和模拟存储库,对吗?我做对了吗?

假设您正在使用最小起订量,请不要尝试模拟扩展方法。

既然您控制了扩展方法的代码,那么通过扩展方法模拟一个安全路径。

在这种情况下,扩展使用GetAsync,这是需要模拟的假设这不是一个扩展。

//...
_repository
.Setup(x => x.GetAsync(It.IsAny<Guid>()))
.ReturnsAsync(GetSamplePhase(newGuid));
//...

它将允许测试在执行时通过GetActiveAsync代码,如果失败,也会抛出异常等,如代码中所述。

相关内容

  • 没有找到相关文章

最新更新