带有模拟存储库的单元测试命令类

时间:2013-12-22 01:43:38

标签: c# unit-testing moq cqrs

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

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

2 个答案:

答案 0 :(得分:2)

您必须模拟数据库层。同样,您也可以使用Mock Repositor层而不是数据库层。

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

答案 1 :(得分:1)

当然你可以模拟数据库(你甚至应该,教科书说)。但是这很快变得非常麻烦,特别是当复杂的数据库约束发挥作用时。

在实践中,拥有本地测试数据库(例如,如果可能的话,使用SQLite或MS SQL CE在内存中)并对整个“持久性堆栈”进行测试(在您的情况下:命令,存储库和数据库)可能更有效率) 一气呵成。这是The Art of Unit Testing一书中推荐的方法,我发现它在实践中非常有用。

相关问题