Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mediatr: Unit Testing behaviors/validation

I have a command/handler that saves an entity to the db, but in my code, it goes through validation first (validation pipeline) using fluentvalidation.

I was able to create a success test to test the handler, but now I would like to make sure the command goes through validation first.

How would I go about doing so? should I be calling the validation independently like i do with my handler? if so how do i do that

here is my code

    [Test]
    public  async Task CreateCoinCommand_Success()
    {
        var context = new Mock<EventsContext>();
        var ownersMock = CreateDbSetMock(new List<Owner>());

        context.Setup(x => x.Owners).Returns(ownersMock.Object);

        var handler = new CreateCoinCommandHandler(context.Object, mapper.Object );


        var cmd = new CreateCoinCommand(1, "sym", "name", null, null, null, 1, "description",
            null, "https://google.com", null, null, null, new []{1,2});

        var cltToken = new System.Threading.CancellationToken();
        var result = await handler.Handle(cmd, cltToken);

        Assert.IsInstanceOf<Unit>(result);
    }

My validator is called CreateCoinCommandValidator

like image 632
Zoinky Avatar asked Oct 16 '22 08:10

Zoinky


1 Answers

Yes, in unit test you need to call validator manually

// Arrange
var validator = new CreateCoinCommandValidator();
var cmd = new CreateCoinCommand(1, "sym", "name", null, null, null, 1, "description",
            null, "https://google.com", null, null, null, new []{1,2});

// Act
var validationResult = await validator.ValidateAsync(cmd);

// Assert
Assert.True(validationResult.IsValid);
...

Also see Default testing extensions

like image 138
Roman Marusyk Avatar answered Oct 19 '22 22:10

Roman Marusyk