invoking an async task on fluentassertion
Asked Answered
N

2

6

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..?

Nitid answered 2/8, 2018 at 20:28 Comment(0)
G
15

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.

Gilthead answered 3/8, 2018 at 6:16 Comment(0)
S
4

Invoking<T> extensoin 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>();
}
Slemmer answered 2/8, 2018 at 21:32 Comment(1)
Thanks! This technique allowed me to keep the Arrange / Act / Assert pattern! :)Rattly

© 2022 - 2024 — McMap. All rights reserved.