我正在使用Moq使用工作單元和通用存儲庫的服務進行單元測試。問題是,在服務類中,當我在調試模式下運行測試時,_subsiteRepository始終爲空。使用Moq的單元測試工作單元和通用存儲庫模式框架
服務類的,我嘲笑
private readonly IRepository<Subsite> _subsiteRepository;
public PlatformService(IUnitOfWork<PlatformContext> unitOfWork)
{
_subsiteRepository = unitOfWork.GetRepository<Subsite>();
}
設置和在這個類是正在測試的方法。問題是_subsiteRepository始終爲空。該方法不僅僅是這個,而是相關的部分。
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'。在需要調用該對象之前,即在「Act」之前,我將移動「PlatformService」的構造。 –