Domanda

My application is designed using the CQRS pattern and repositories, how can I create unit tests for my command classes without connecting to the database?

We are using Moq to create mocks of our repositories.

È stato utile?

Soluzione

You have to mock your Database Layer. Similarly you can Mock Repositor layer also instead of Database Layer.

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

Altri suggerimenti

Of course you can mock the database (and you even should, says the textbook). But this soon gets very cumbersome, especially when complex database constraints are into play.

In practice it might be more productive to have a local test database (e.g. in-memory with SQLite or MS SQL CE, if possible) and test against the entire 'persistence stack' (in your case: Commands, Repositories AND database) in one go. This is the method that is recommended in the book The Art of Unit Testing, and I found it very helpful in practice.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top