我正在对使用Moq的工作单元和通用存储库的服务进行单元测试.问题是在服务类中,当我在调试模式下运行测试时,_subsiteRepository始终为空.
I am unit testing a Service which is using the a Unit of Work and Generic Repository using Moq. The problem is that in the service class the _subsiteRepository is always null when I run the test in debug mode.
我正在嘲笑的服务类的设置
The setup of the Service Class I am mocking
private readonly IRepository<Subsite> _subsiteRepository; public PlatformService(IUnitOfWork<PlatformContext> unitOfWork) { _subsiteRepository = unitOfWork.GetRepository<Subsite>(); }以及正在测试的此类中的方法.问题在于_subsiteRepository始终为null.该方法的作用还不止于此,但这是相关的部分.
and the method in this class that am testing. The problem is that _subsiteRepository is always null. The method does more than this but this is the relevant part.
public async Task<IEnumerable<Subsite>> GetSubsites() { // Get Subsites var subsites = await _subsiteRepository .GetAll() .ToListAsync(); }最后这是我正在运行的测试:
Finally this is the test I am running:
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模拟之前调用了PlatformService构造函数.
Move creation of the _platformService after Arrange step. Because you call the PlatformService constructor before unitOfWork mock is setup.
_subsiteRepository = new Mock<IRepository<Subsite>>(); _unitOfWork = new Mock<IUnitOfWork<PlatformContext>>(); // 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 _platformService = new PlatformService(_unitOfWork.Object); var subsites = await _platformService.GetSubsites(null, null); // Assert Assert.NotNull(subsites);更多推荐
使用Moq进行单元测试的工作单元和通用存储库模式框架
发布评论