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

标签 c# unit-testing exception void nsubstitute

使用 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/

相关文章:

Java - 字符串输入异常处理

asp.net - 操作可能会破坏 ASP.NET 运行时的稳定性

javascript - 如何使用 Controller 中的对象创建 js

unit-testing - 将 Specflow 场景用于集成测试和单元测试

c# - 通过 Windows Live ID 登录到桌面应用程序

angular - fakeAsync() 测试助手需要错误 : zone-testing. js,但找不到。使用 serenityJS+Jasmine 在 Angular webapp 上运行测试时

c++ - 谷歌模拟 : Mock private variable member that is instantiated in target class's constructor

c++ - std::function 的异常安全

c# - foreach循环读取xml子节点

c# - 当我不知道它可能抛出的位置时如何记录异常?