Reputation: 1664
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?
Upvotes: 38
Views: 36719
Reputation: 11
This simple line worked for me:
Assert.ThrowsAsync<Exception>(async () => await _service.MyAsyncFunction());
Upvotes: 1
Reputation: 309
in my case it worked as follows
_substiture.GetAsync<SomeType?>("").ThrowsAsyncForAnyArgs(new CustomException(System.Net.HttpStatusCode.InternalServerError, "some message"));
Upvotes: 1
Reputation: 5230
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.
Upvotes: 47
Reputation: 277
This is what worked for me:
myService.GetAllAsync().Returns(Task.Run(() => ThrowException()));
private List<object> ThrowException()
{
throw new Exception();
}
Upvotes: 5
Reputation: 1664
This worked:
using NSubstitute.ExceptionExtensions;
myService.GetAllAsync().Throws(new Exception());
Upvotes: 31