我正在对使用Moq的工作单元和通用存储库的服务进行单元测试。问题是,在调试模式下运行测试时,服务类中的_subsiteRepository始终为null。
我正在模拟的服务类的设置。
我正在测试的这个类中的方法。问题是_subsiteRepository始终为null。该方法做了更多的事情,但这是相关的部分。
最后,这是我正在运行的测试:
我正在模拟的服务类的设置。
private readonly IRepository<Subsite> _subsiteRepository;
public PlatformService(IUnitOfWork<PlatformContext> unitOfWork)
{
_subsiteRepository = unitOfWork.GetRepository<Subsite>();
}
我正在测试的这个类中的方法。问题是_subsiteRepository始终为null。该方法做了更多的事情,但这是相关的部分。
public async Task<IEnumerable<Subsite>> GetSubsites()
{
// Get Subsites
var subsites = await _subsiteRepository
.GetAll()
.ToListAsync();
}
最后,这是我正在运行的测试:
private readonly Mock<IRepository<Subsite>> _subsiteRepository;
private readonly Mock<IUnitOfWork<PlatformContext>> _unitOfWork;
private readonly PlatformService _platformService;
_subsiteRepository = new Mock<IRepository<Subsite>>();
_unitOfWork = new Mock<IUnitOfWork<PlatformContext>>();
_platformService = new PlatformService(_unitOfWork.Object);
// Arrange
var fakeSubsites = new List<Subsite>
{
new Subsite {IDSubsite = new Guid(), Title = "Subsite One"}
}.AsQueryable();
_unitOfWork.Setup(x => x.GetRepository<Subsite>()).Returns(_subsiteRepository.Object);
_unitOfWork.Setup(x => x.GetRepository<Subsite>().GetAll()).Returns(fakeSubsites);
// Act
var subsites = await _platformService.GetSubsites(null, null);
// Assert
Assert.NotNull(subsites);
PlatformService
之后,您设置了unitOfWork.GetRepository
。因此,在PlatformService
的构造函数中,您实际上永远不会得到subsiteRepository.Object
。我建议将PlatformService
的构造放在需要调用对象之前,即在Act
之前。 - Stephen RossMock<ISubsite>
呢?我猜存储库有一个接口。 - MZawg