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

Bra*_*don 13 .net c# asynchronous task nsubstitute

使用NSubstitute,如何模拟返回任务的方法中抛出的异常?

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

Task<List<object>> GetAllAsync();
Run Code Online (Sandbox Code Playgroud)

以下是NSubstitute文档如何模拟抛出非void返回类型的异常.但这不编译:(

myService.GetAllAsync().Returns(x => { throw new Exception(); });
Run Code Online (Sandbox Code Playgroud)

那你怎么做到这一点?

Bra*_*don 17

这有效:

using NSubstitute.ExceptionExtensions;

myService.GetAllAsync().Throws(new Exception());
Run Code Online (Sandbox Code Playgroud)

  • 这是一个同步异常,请参阅我的答案以获取正确的方法。 (3认同)
  • 最大的问题是在错误的时间抛出了异常。`var t = AsyncMethod(); 等待。使用异步方法,等待任务时会引发异常,您的方法会立即引发异常。引发哪种异常取决于很多事情。 (2认同)

dst*_*stj 14

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

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

假设您有这段代码, GetAllAsync()

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

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


Mak*_*awa 5

这对我有用:

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

private List<object> ThrowException()
{
        throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)