繁体   English   中英

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

[英]NSubstitute - mock throwing an exception in method returning void

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

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

    void Add();

这是NSubstitute文档所说的针对void返回类型模拟抛出异常的方式。 但这不会编译:(

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

那么,您如何做到这一点呢?

从替代配置中的.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

与显示的文档相同,将为带参数的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

假设接口是

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM