NSubstitute - 模拟在返回void的方法中抛出异常

Kav*_*tty 2 c# unit-testing exception void nsubstitute

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

假设我们的方法签名看起来像这样:

    void Add();
Run Code Online (Sandbox Code Playgroud)

以下是NSubstitute文档如何模拟抛出void返回类型的异常.但这不编译:(

    myService
        .When(x => x.Add(-2, -2))
        .Do(x => { throw new Exception(); });
Run Code Online (Sandbox Code Playgroud)

那你怎么做到这一点?

Fab*_*bio 6

.Add替换配置中的方法中删除参数.
下面的示例将编译并为没有参数的void方法工作

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

Action action = () => fakeService.Add();
action.ShouldThrow<ArgumentException>(); // Pass
Run Code Online (Sandbox Code Playgroud)

与显示的文档相同,将使用参数编译void方法

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
Run Code Online (Sandbox Code Playgroud)

假设接口是

public interface IYourService
{
    void Add();
    void Add(int first, int second);
}
Run Code Online (Sandbox Code Playgroud)