Skip to content

UnitTesting

Anrijs Vitolins edited this page May 20, 2021 · 2 revisions

Abstracting DB in unit-testing

When ICommandQueryContext is injected into business logic classes, then it is the one we should abstract (mock) away, so we can deal only with code in particular logic.

There are many ready mocking libraries, the most popular being MOQ, so we are using examples on this one. (and xUnit as engine).

public class SomeTests
{
    private readonly Mock<ICommandQueryContext> _cqrsMock;
    private readonly SomeLogic _sut;
    
    // Constructor (run for each test in this class)
    public SomeTests
    {
        _cqrsMock = new Mock<ICommandQueryContext>();
        _sut = new SomeLogic(_cqrsMock.Object); // injecting mock instead of real context
    }
    
    [Fact]
    public async Task Some_Logic_Test()
    {
        // arrange -setting up particular query call to return specified data.
        var preparedData = {some data, list or object as if returned from database call};
        _cqrsMock.Setup(cqrs => cqrs.QueryAsync(It.IsAny<SomeQueryClass>()))
            .Returns(Task.FromResult(preparedData));
            
        // act - calling logic method
        var result = _sut.CallSomeMethod();
        
        // assert (FluentAssertions) - check the result
        result.Should().NotBeNull();
        result.Should()...
        
        // asserting that Query was actualy called by logic (once)
        _cqrsMock.Verify(cqrs => cqrs.QueryAsync(It.IsAny<SomeQueryClass>()), Times.Once);
    }
}