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)
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>(),因为它同步抛出异常,不与接受的答案。
这对我有用:
myService.GetAllAsync().Returns(Task.Run(() => ThrowException()));
private List<object> ThrowException()
{
throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8836 次 |
| 最近记录: |