Reputation: 8177
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.
Upvotes: 2
Views: 1950
Reputation: 6563
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);
}
}
Upvotes: 3
Reputation: 11717
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.
Upvotes: 1