我正在使用Moq对使用工作单元和通用存储库的服务进行单元测试。问题是,在服务类中,当我在调试模式下运行测试时,_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);
答案 0 :(得分:2)
在排列步骤后移动_platformService
的创建。因为在设置PlatformService
mock之前调用unitOfWork
构造函数。
_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);