c# - 使用 Moq 的单元测试工作单元和通用存储库模式框架

标签 c# unit-testing moq

我正在对一个服务进行单元测试,该服务使用工作单元和使用最小起订量的通用存储库。问题是在服务类中,当我在 Debug模式下运行测试时,_subsiteRepository 始终为 null。

我正在模拟的服务类的设置

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

最佳答案

在 Arrange 步骤之后移动 _platformService 的创建。因为您在设置 unitOfWork mock 之前调用了 PlatformService 构造函数。

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

关于c# - 使用 Moq 的单元测试工作单元和通用存储库模式框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986378/

相关文章:

java - 如何解决 "to create a new mock, the existing mock registration must be deregistered"

android - 单元测试作用域 View 模型的最佳方法

c# - 使用 Microsoft Moles 模拟一个简单的类

c# - 单元测试抽象类和其中的 protected 方法

c# - 使用 Redis 实现排序、搜索和分页以获得最佳性能的最佳方式

c# - 如何获得应用程序启动所需的时间?

ios - 旧版 ObjC/Swift 代码库使 `swift_checkMetadataState` : how to disentangle app/test targets? 中的测试崩溃

c# - 使用 Moq 模拟扩展方法

c# - XSD 的属性以防止 XSD.exe FieldSpecified 标志

c# - 浏览器成功但 HttpWebRequest 失败(超时)