2016-07-12 48 views
4

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

比方说,我们的方法签名看起来是这样的:

Task<List<object>> GetAllAsync(); 

这里的NSubstitute文档怎么说嘲笑了非空的返回类型抛出异常。但是,这并不编译:(

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

那么,你如何做到这一点

回答

8

这工作:

using NSubstitute.ExceptionExtensions; 

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

这是对我工作:

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

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