所以我試圖模擬我的服務,這是真正的代碼:
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));
它說它不能將 Mocked 存盤庫轉換為真實的存盤庫,但我不應該在這里使用模擬存盤庫嗎?
我想要實作的是測驗我的真實服務并模擬存盤庫,對嗎?我在這里做對了嗎?
uj5u.com熱心網友回復:
假設您使用的是 MOQ,請不要嘗試模擬擴展方法。
由于您控制擴展方法的代碼,然后通過擴展方法模擬安全路徑。
擴展GetAsync在這種情況下使用,假設它也不是擴展,則需要對其進行模擬。
//...
_repository
.Setup(x => x.GetAsync(It.IsAny<Guid>()))
.ReturnsAsync(GetSamplePhase(newGuid));
//...
它將允許測驗在執行時通過GetActiveAsync代碼,如果測驗失敗,也會按照代碼中的描述拋出例外等。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/316772.html
