Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute - mock throwing an exception in method returning Task

Using NSubstitute, how do you mock an exception being thrown in a method returning a Task?

Let's say our method signature looks something like this:

Task<List<object>> GetAllAsync(); 

Here's how NSubstitute docs say to mock throwing exceptions for non-void return types. But this doesn't compile :(

myService.GetAllAsync().Returns(x => { throw new Exception(); }); 

So how do you accomplish this?

like image 854
Brandon Avatar asked Jul 12 '16 21:07

Brandon


People also ask

How do you throw an exception in Nsubstitute?

Normally, for synchronous calls, you can just add a . Throws<TException>() after the method you want to mock throwing an exception (or . ThrowsForAnyArgs<TException>() if you don't care about the input arguments).


1 Answers

Actually, the accepted answer mocks a synchronous exception being thrown, that is not the real async behavior. The correct way to mock is:

var myService = Substitute.For<IMyService>(); myService.GetAllAsync()          .Returns(Task.FromException<List<object>>(new Exception("some error"))); 

Let's say you had this code and GetAllAsync()

try {     var result = myService.GetAllAsync().Result;     return result; } catch (AggregateException ex) {     // whatever, do something here } 

The catch would only be executed with Returns(Task.FromException>(), not with the accepted answer since it synchronously throws the exception.

like image 64
dstj Avatar answered Sep 18 '22 06:09

dstj