c# - 使用模拟存储库进行单元测试命令类

标签 c# unit-testing moq cqrs

我的应用程序是使用 CQRS 模式和存储库设计的,如何在不连接到数据库的情况下为我的命令类创建单元测试?

我们正在使用 Moq 来创建我们存储库的模拟。

最佳答案

你必须模拟你的数据库层。同样,您也可以模拟存储库层而不是数据库层。

[TestClass]
public class TestCommandServiceTests
{
    private readonly TestService _testService;
    private readonly ITestRepositor _testRepository;
    private readonly Mock<IDatabaseLaye> _mock;

    [SetUp]
    public void Setup()
    {
        _mock = new Mock<IDatabaseLayer>();
        _testRepository = new TestRepository(_mock);
        _testService = new TestService(_testRepository);
    }

    [Test]
    public void TestMethod_ValidRequest_ShouldTestSuccessfully()
    {
        // Arrange
        var request = new TestMethodRequest();
        this._mock.Setup(c => c.TestSPMethod(null)).Returns(1000);

        // Act
        var response = _testService.TestMethod(request);

        // Assert
        Assert.IsNotNull(response);
        Assert.AreEqual(1000, response.Id);
    }
}

关于c# - 使用模拟存储库进行单元测试命令类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20725373/

相关文章:

C# MVC 4 多线程和 Web 请求

c# - 创建 C# Func<> 类型别名

C# 模拟测试 - Moq 列表不能是 'foreach',告诉 'NullReferenceException'

c# - 如何用 C# 代码编写这个 DOS 命令?

C# 通过 http 传输序列化 Protobuf 数据的最佳方式

javascript - 为什么我的 jest.mock 中的 Promise reject() 会转到 then() 而不是 catch()?

c# - 如何对 OData 客户端进行单元测试?

c# - 是否可以(使用 Moq)对带有 Lambda 参数的方法调用进行 stub ?

unit-testing - 32 位/64 位应用程序的单元测试

c# - 用于测试调用异步方法的 ICommand 的模式