使用 NSubstitute,如何模拟在返回 void 的方法中抛出的异常?
假设我们的方法签名看起来像这样:
void Add();
下面是 NSubstitute 文档如何模拟 void 返回类型的抛出异常。但这不编译:(
myService
.When(x => x.Add(-2, -2))
.Do(x => { throw new Exception(); });
那么你是如何做到这一点的呢?
最佳答案
从 中删除参数。在替代配置中添加
方法。
下面的示例将编译并为没有参数的 void 方法工作
var fakeService = Substitute.For<IYourService>();
fakeService.When(fake => fake.Add()).Do(call => { throw new ArgumentException(); });
Action action = () => fakeService.Add();
action.ShouldThrow<ArgumentException>(); // Pass
与文档中显示的一样,将为带参数的 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
假设接口(interface)是
public interface IYourService
{
void Add();
void Add(int first, int second);
}
关于c# - NSubstitute - 模拟在返回 void 的方法中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44325758/