使用Moq进行单元测试的工作单元和通用存储库模式框架 [英] Unit Testing Unit of Work and Generic Repository Pattern framework using Moq

查看:63
本文介绍了使用Moq进行单元测试的工作单元和通用存储库模式框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对使用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进行单元测试的工作单元和通用存储库模式框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆