2017-06-02 76 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); 
}