Roelant M
Roelant M

Reputation: 1716

invoking an async task on fluentassertion

probably a simple one, but cant get it to work;

i've changed the signature one on the methods to Task

On my unit tests i am using fluent assertions.

but cant get this to work:

        _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");

the MapToCatalogVehiclesAsync is the async method, but i need to await it, but awaiting and asyncing the invocation, doesnt seem to do it.. someone..?

Upvotes: 7

Views: 10229

Answers (2)

Fabio
Fabio

Reputation: 32453

Invoking<T> extension method returns Action which with asynchronous method is equivalent to async void - so exceptions will not be awaited.

As workaround you can wrap method under the test to a Func<Task>.

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

Upvotes: 5

Dennis Doomen
Dennis Doomen

Reputation: 8909

Although Fabio's answer is correct as well, you can also do this:

_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");

And as a side-note, I suggest to always use wildcards in WithMessage. See point 10 from this blog post.

Upvotes: 15

Related Questions