2017-06-02 77 views
0

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

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

void Add(); 

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

myService 
     .When(x => x.Add(-2, -2)) 
     .Do(x => { throw new Exception(); }); 

那么,你如何做到这一点?

+0

删除参数,因为你的方法不会让他们 – Fabio

回答

2

在替代配置.Add方法删除参数。
下面的示例将编译并没有参数

为无效方法工作
var fakeService = Substitute.For<IYourService>(); 
fakeService.When(fake => fake.Add()).Do(call => { throw new ArgumentException(); }); 

Action action =() => fakeService.Add(); 
action.ShouldThrow<ArgumentException>(); // Pass 

而且相同所示将编译用于与参数空隙方法文档

var fakeService = Substitute.For<IYourService>(); 
fakeService.When(fake => fake.Add(2, 2)).Do(call => { throw new ArgumentException(); }); 

Action action =() => fakeService.Add(2, 2); 
action.ShouldThrow<ArgumentException>(); // Pass 

假设该接口是

public interface IYourService 
{ 
    void Add(); 
    void Add(int first, int second); 
}