使用Moq进行单元测试的工作单元和通用存储库模式框架

编程入门 行业动态 更新时间:2024-10-24 20:16:51
本文介绍了使用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进行单元测试的工作单元和通用存储库模式框架

本文发布于:2023-06-13 09:30:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/678920.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框架   单元测试   模式   工作   Moq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!