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?

3
  • 2
    await unwraps the exception, just catch the exception your method throws Commented Jan 22, 2019 at 21:08
  • Dang.. I hate it when I miss something really simple :). Thank you! Make it an answer and I'll accept. Commented Jan 22, 2019 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? Commented Jan 22, 2019 at 21:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.