在Java中排除异常,怎么样? [英] Asserting exceptions in Java, how?

查看:197
本文介绍了在Java中排除异常,怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个概念上愚蠢的问题,但也可能不是,因为我还是一个学生,我想我应该没问题。

This might be a conceptually stupid question, but it also might not and since I am still a student I think I should I have no problem asking.

想像你有一种方法,如果给定某些条件,它将抛出NumberFormatException。我想写一个单元测试来查看异常是否正确钍。如何达到这个目的?

Imagine you have a method that if given certain conditions it will throw an NumberFormatException. I want to write a Unit Test to see if the exception is being correctly thorwn. How can I achieve this?

我正在使用JUnit写单元测试。

P.S. I am using JUnit to write the Unit Tests.

谢谢。

推荐答案

p>如其他海报所示,如果您使用JUnit4,则可以使用注释:

As other posters suggested, if you are using JUnit4, then you can use the annotation:

@Test(expected=NumberFormatException.class);

但是,如果您使用的是旧版本的JUnit,或者如果要执行多个异常在相同的测试方法中的断言,那么标准成语是:

However, if you are using an older version of JUnit, or if you want to do multiple "Exception" assertions in the same test method, then the standard idiom is:

try {
   formatNumber("notAnumber");
   fail("Expected NumberFormatException");
catch(NumberFormatException e) {
  // no-op (pass)
}

这篇关于在Java中排除异常,怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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