1

I'm setting up a consumer for a WebAPI and writing some unit tests. The 'act' portion of my test is as follows:

var dta = await service.AuthenticateAsync(customerId, userName, password, machineId);           

try
{
    service.AuthenticateAsync(customerId, userName, password, machineId).Wait();
}
catch (AggregateException ex)
{
    exUnauthorized = ex;
}
try
{
    httpTest.SimulateTimeout();
    await service.AuthenticateAsync(customerId, userName, password, machineId);
 }
 catch (AggregateException ex)
 {
     exTimeout = ex;
 }

I set up Flurl HttpTest as follows:

httpTest.RespondWithJson(auth)
                .RespondWith(status: (int)HttpStatusCode.Unauthorized);

In order to get a first response of success and second of unauthorized. As you can see later in the code I set up timeout to test that (if I set it up initially it seems to time out for all requests).

The first call succeeds. The second call where I use Wait() in the try block works and catches the aggregate exception. The second call where I use await does not catch the exception; it fails the unit test with the exception thrown by the method.

What am I missing? Why doesn't the await call work right?

sfaust
  • 2,089
  • 28
  • 54
  • 2
    `await` [unwraps the exception](https://binary-studio.com/2014/06/04/5-things-you-should-know-about-asyncawait-in-c/), just catch the exception your method throws – JSteward Jan 22 '19 at 21:08
  • Dang.. I hate it when I miss something really simple :). Thank you! Make it an answer and I'll accept. – sfaust Jan 22 '19 at 21:15
  • Downvoter, I did Google for a while and didn't find anything, sorry. What was the issue with the question that earned a down vote? – sfaust Jan 22 '19 at 21:17

1 Answers1

2

await doesn't wrap exceptions in an AggregateException, as it is intended for use in asynchronous code. Wait() and Result do wrap underlying exceptions in an AggregateException, as they are intended for use in parallel code.

Technically, it's not that await unwraps the exception; it just doesn't wrap it like Wait/Result do.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810