NSubstitute - 模拟在返回任务的方法中抛出异常

NSubstitute - mock throwing an exception in method returning Task

使用 NSubstitute,如何模拟在 return 执行任务的方法中抛出的异常?

假设我们的方法签名看起来像这样:

Task<List<object>> GetAllAsync();

下面是 NSubstitute 文档如何模拟非 void return 类型的抛出异常。但这不编译:(

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

那么你是如何做到这一点的呢?

这有效:

using NSubstitute.ExceptionExtensions;

myService.GetAllAsync().Throws(new Exception());

这对我有用:

myService.GetAllAsync().Returns(Task.Run(() => ThrowException()));

private List<object> ThrowException()
{
        throw new Exception();
}

实际上,接受的答案模拟了抛出的同步异常,这不是 真实 async 行为。正确的mock方式是:

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

假设您有此代码并且 GetAllAsync()

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

catch 只会用 Returns(Task.FromException>() 执行,而不是用接受的答案执行,因为它会同步抛出异常。