Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# use moq to throw exception from async method

I am using the Moq library as a mocking framework together with nunit. I am having trouble to figure out how to setup my mock object to throw an exception from an async method that returns a Task.

any help is appreciated

like image 611
Sam Avatar asked Aug 13 '16 14:08

Sam


1 Answers

Async methods don't normally throw exceptions directly - they return tasks which end up being faulted. The simplest way to create such a task is to use Task.FromException.

You haven't given many details in your question, but I suspect if you just make your mock return the result of Task.FromException with the exception you want, that will simulate the error appropriately. The only downside is that the task will immediately be faulted, which will only test the "fast path" of anything awaiting it - it won't test the situation where the exception is only thrown later. To do that, you could write your own little async helper method:

// Create a non-generic one if you want, too
private static async Task<T> DelayFaultedTask(Exception e)
{
    await Task.Yield();
    throw e;
}

Then call that to obtain a "delay-faulted" task to return from your mock.

like image 132
Jon Skeet Avatar answered Oct 03 '22 05:10

Jon Skeet