Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test this async method which (correctly) throws an exception?

I have the following method in an interface..

Task<SearchResult<T>> SearchAsync(TU searchOptions);

works great.

Now i'm trying to make a unit test to test when something goes wrong - and the code throws an exception.

In this case, I've setup my method to throw an HttpRequestException. My unit test fails to say that I threw that exception ..

var result = Should.Throw<HttpRequestException>
    (async () => await service.SearchAsync(searchOptions));

the error message from the unit test is

Shouldly.ChuckedAWobbly
var result = Should
throw
System.Net.Http.HttpRequestException
but does not

So the assertion framework is saying: You've expected an exception, but none was thrown.

When I step -through- the code, the exception is 100% thrown.

Can anyone see what i've done wrong with my unit test code, please?

like image 347
Pure.Krome Avatar asked Mar 14 '14 10:03

Pure.Krome


1 Answers

Test it like this:

var result = Should.Throw<HttpRequestException>
    (() => service.SearchAsync(searchOptions).Result);

Or:

var result = Should.Throw<HttpRequestException>
    (() => service.SearchAsync(searchOptions).Wait());

Otherwise, your Should.Throw returns before the async lambda has completed.

like image 183
avo Avatar answered Oct 22 '22 04:10

avo