[英]NSubstitute - mock throwing an exception in method returning Task
使用NSubstitute ,你如何模拟在返回任务的方法中抛出的异常?
假设我们的方法签名看起来像这样:
Task<List<object>> GetAllAsync();
以下是 NSubstitute 文档如何模拟非 void 返回类型的抛出异常。 但这不能编译:(
myService.GetAllAsync().Returns(x => { throw new Exception(); });
那么你是如何做到这一点的呢?
这工作:
using NSubstitute.ExceptionExtensions;
myService.GetAllAsync().Throws(new Exception());
实际上,接受的答案模拟了抛出的同步异常,这不是真正的 async
行为。 模拟的正确方法是:
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>()
来执行,而不是接受的答案,因为它会同步引发异常。
这对我有用:
myService.GetAllAsync().Returns(Task.Run(() => ThrowException()));
private List<object> ThrowException()
{
throw new Exception();
}
就我而言,它的工作方式如下
_substiture.GetAsync<SomeType?>("").ThrowsAsyncForAnyArgs(new CustomException(System.Net.HttpStatusCode.InternalServerError, "some message"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.