简体   繁体   English

您如何测试私有方法内部的异常,该方法由公共 void 使用?

[英]How do you test for an exception that is inside of a private method, which is used by a public void?

As the title says, I am testing that an exception is thrown inside a private method, which is then accessed by a public void.正如标题所说,我正在测试是否在私有方法中抛出异常,然后由公共 void 访问该异常。 Any help would be appreciated.任何帮助,将不胜感激。

You can use Assert.Throws to check that an exception is thrown.您可以使用Assert.Throws来检查是否抛出了异常。 If the exception is not thrown then the test will fail:如果未抛出异常,则测试将失败:

var foo = new Foo();
Assert.Throws<MyException>(() => foo.DoSomething());

This test requires that MyException is thrown.此测试要求抛出MyException If another exception (even one derived from MyException ) is thrown then the test will fail.如果抛出另一个异常(甚至是从MyException派生的MyException ),则测试将失败。

If you want to test for an exception or anything derived from that exception then you can use Assert.Catch :如果要测试异常或从该异常派生的任何内容,则可以使用Assert.Catch

var foo = new Foo();
Assert.Catch<MyException>(() => foo.DoSomething());

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

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