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.