Unit Testing Unit of Work and Generic Repository Pattern framework using Moq

会有一股神秘感。 提交于 2019-12-06 13:32:21

问题


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>();
}

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);

回答1:


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);


来源:https://stackoverflow.com/questions/35986378/unit-testing-unit-of-work-and-generic-repository-pattern-framework-using-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!