Mediatr:单元测试行为/验证

时间:2019-01-03 14:40:33

标签: c# .net-core fluentvalidation mediatr

我有一个将实体保存到数据库的命令/处理程序,但是在我的代码中,它首先使用fluentvalidation进行了验证(验证管道)。

我能够创建一个成功测试来测试处理程序,但是现在我想确保命令首先通过验证。

我将如何去做?我应该像处理程序一样独立地调用验证吗?如果可以的话,我该怎么做

这是我的代码

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

我的验证人称为CreateCoinCommandValidator

1 个答案:

答案 0 :(得分:0)

是的,在单元测试中,您需要手动调用验证器

// 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);
...

另请参见Default testing extensions

相关问题