在 Java 中断言异常,如何?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4047472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:55:17  来源:igfitidea点击:

Asserting exceptions in Java, how?

javaunit-testingexception-handlingjunit

提问by nunos

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.

这可能是一个概念上的愚蠢问题,但也可能不是,因为我仍然是一名学生,所以我认为我应该没有问题。

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?

假设您有一个方法,如果给定某些条件,它将抛出 NumberFormatException。我想编写一个单元测试来查看异常是否被正确触发。我怎样才能做到这一点?

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

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

Thanks.

谢谢。

采纳答案by Michael D

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

正如其他海报所建议的那样,如果您使用的是 JUnit4,那么您可以使用注释:

@Test(expected=NumberFormatException.class);

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:

但是,如果您使用的是旧版本的 JUnit,或者您想在同一个测试方法中执行多个“异常”断言,那么标准习惯用法是:

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

回答by Jon

Use @Test(expected=IOException.class)

使用@Test(expected=IOException.class)

http://junit.sourceforge.net/doc/faq/faq.htm#tests_7

http://junit.sourceforge.net/doc/faq/faq.htm#tests_7

This is fine if you have one expected exception. An alternative strategy is to add an Assert.fail() at the end of the test method. If an exception isn't thrown then the test will fail accordingly. e.g.

如果您有一个预期的异常,这很好。另一种策略是在测试方法的末尾添加一个 Assert.fail()。如果未抛出异常,则测试将相应失败。例如

@Test
public void testIOExceptionThrown() {      
   ftp.write(); // will throw IOException      
   fail();
}

回答by Feanor

Assuming you are using JUnit 4, call the method in your test in a way that causes it to throw the exception, and use the JUnit annotation

假设您使用的是 JUnit 4,请以导致它抛出异常的方式调用测试中的方法,并使用 JUnit 注释

@Test(expected = NumberFormatException.class)

If the exception is thrown, the test will pass.

如果抛出异常,则测试将通过。

回答by Adam

You can do this:

你可以这样做

 @Test(expected=IndexOutOfBoundsException.class)
    public void testIndexOutOfBoundsException() {
        ArrayList emptyList = new ArrayList();
        Object o = emptyList.get(0);
    }

回答by duffymo

Add this annotation before your test method; it'll do the trick.

在您的测试方法之前添加此注释;它会做的伎俩。

@Test(expected = java.lang.NumberFormatException.class)
public void testFooMethod() {
    // Add code that will throw a NumberFormatException
}

回答by NamshubWriter

If you can use JUnit 4.7, you can use the ExpectedExceptionRule

如果可以使用 JUnit 4.7,则可以使用ExpectedException规则

@RunWith(JUnit4.class)
public class FooTest {
  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void doStuffThrowsIndexOutOfBoundsException() {
    Foo foo = new Foo();

    exception.expect(IndexOutOfBoundsException.class);
    exception.expectMessage("happened?");
    exception.expectMessage(startsWith("What"));
    foo.doStuff();
  }
}

This is much better than @Test(expected=IndexOutOfBoundsException.class)because the test will fail if IndexOutOfBoundsExceptionis thrown before foo.doStuff()

这比@Test(expected=IndexOutOfBoundsException.class)因为如果IndexOutOfBoundsException之前抛出测试将失败要好得多foo.doStuff()

See this articleand the ExpectedException JavaDocfor details

有关详细信息,请参阅本文ExpectedException JavaDoc

回答by rwitzel

A solution that is not bound to a particular JUnit version is provided by catch-exceptionwhich has been made to overcome some disadvantages that are inherent in the JUnit mechanisms.

不绑定到特定 JUnit 版本的解决方案由catch-exception提供,它被用来克服 JUnit 机制中固有的一些缺点。