在 fluentassertion 上调用异步任务

invoking an async task on fluentassertion

可能是一个简单的,但无法让它工作;

我已将方法上的签名一更改为任务

在我的单元测试中,我使用了流畅的断言。

但无法让它工作:

        _catalogVehicleMapper
            .Invoking(m => m.MapToCatalogVehiclesAsync(searchResult, filtersInfo, request, default(CancellationToken)))
            .Should().Throw<ArgumentException>()
            .WithMessage("One of passed arguments has null value in mapping path and can not be mapped");

MapToCatalogVehiclesAsync 是异步方法,但我需要等待它,但等待和异步调用似乎并没有这样做.. 有人..?

Invoking<T> extensoin 方法 returns Action 异步方法等同于 async void - 因此不会等待异常。

作为解决方法,您可以将测试下的方法包装到 Func<Task>

[Fact]
public async Task ThrowException()
{
    Func<Task> run = 
        () => _catalogVehicleMapper.MapToCatalogVehiclesAsync(
            searchResult, 
            filtersInfo, 
            request, 
            default(CancellationToken));

    run.Should().Throw<ArgumentException>();
}

虽然法比奥的回答也是正确的,但你也可以这样做:

_catalogVehicleMapper
   .Awaiting(m => m.MapToCatalogVehiclesAsync(searchResult, filtersInfo, request, default(CancellationToken)))
   .Should().Throw<ArgumentException>()
   .WithMessage("One of passed arguments has null value in mapping path and can not be mapped");

作为旁注,我建议始终在 WithMessage 中使用通配符。请参阅 this blog post.

中的第 10 点