使用JUnit 4注释测试多个异常 [英] Testing for multiple exceptions with JUnit 4 annotations

查看:153
本文介绍了使用JUnit 4注释测试多个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在单个JUnit单元测试中测试多个异常吗?我知道一个可以使用的例外,例如

Is it possible to test for multiple exceptions in a single JUnit unit test? I know for a single exception one can use, for example

    @Test(expected=IllegalStateException.class)

现在,如果我想测试另一个异常(例如,NullPointerException),可以在相同的注释中完成,不同的注释或者是否需要完全编写另一个单元测试?

Now, if I want to test for another exception (say, NullPointerException), can this be done in the same annotation, a different annotation or do I need to write another unit test completely?

推荐答案

你真的想让测试做一个事情,并测试。如果您不确定将要抛出哪个异常,那听起来不是一个很好的考验。

You really want the test to do one thing, and to test for that. If you're not sure as to which exception is going to be thrown, that doesn't sound like a good test to me.

例如。 (伪代码)

try {
   badOperation();
   /// looks like we succeeded. Not good! Fail the test
}
catch (ExpectedException e) {
   // that's fine
}
catch (UnexpectedException e) {
   // that's NOT fine. Fail the test
}

所以如果你想测试你的方法抛出2个不同的异常(对于2组输入),那么您将需要2次测试。

so if you want to test that your method throws 2 different exceptions (for 2 sets of inputs), then you'll need 2 tests.

这篇关于使用JUnit 4注释测试多个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆