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

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow