在Java中断言exception,如何?
这可能是一个概念上愚蠢的问题,但也可能没有,因为我还是学生,我想我应该没问题。
想象一下,如果给定某些条件,它将抛出一个NumberFormatException。 我想编写一个unit testing来查看exception是否正确。 我怎样才能做到这一点?
PS我正在使用JUnit编写unit testing。
谢谢。
正如其他海报所建议的那样,如果您使用的是JUnit4,那么您可以使用注释:
@Test(expected=NumberFormatException.class);
但是,如果您使用的是旧版本的JUnit,或者您想在同一测试方法中执行多个“exception”断言,则标准惯用法是:
try { formatNumber("notAnumber"); fail("Expected NumberFormatException"); catch(NumberFormatException e) { // no-op (pass) }
假设您正在使用JUnit 4,请以导致它抛出exception的方式调用测试中的方法,并使用JUnit注释
@Test(expected = NumberFormatException.class)
如果抛出exception,测试将通过。
如果可以使用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(); } }
这比@Test(expected=IndexOutOfBoundsException.class)
要好得多,因为如果在foo.doStuff()
之前抛出IndexOutOfBoundsException
,测试将失败
有关详细信息,请参阅本文和ExpectedException JavaDoc
你可以这样做 :
@Test(expected=IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); }
使用@Test(expected = IOException.class)
http://junit.sourceforge.net/doc/faq/faq.htm#tests_7
如果您有一个预期的exception,这很好。 另一种策略是在测试方法的末尾添加Assert.fail()。 如果未抛出exception,则测试将相应失败。 例如
@Test public void testIOExceptionThrown() { ftp.write(); // will throw IOException fail(); }
在测试方法之前添加此注释; 它会做的伎俩。
@Test(expected = java.lang.NumberFormatException.class) public void testFooMethod() { // Add code that will throw a NumberFormatException }
catch-exception提供了一个未绑定到特定JUnit版本的解决方案,该解决方案旨在克服JUnit机制中固有的一些缺点。