2010-10-28 75 views
9

这可能是一个概念上愚蠢的问题,但它也可能不是,因为我仍然是一名学生,我认为我应该没有问题要求。在Java中声明异常,如何?

想象一下,你有一个方法,如果给定某些条件,它会抛出一个NumberFormatException异常。我想编写一个单元测试来查看异常是否正确地被刺穿。我怎样才能做到这一点?

P.S.我正在使用JUnit编写单元测试。

谢谢。

回答

29

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

@Test(expected=NumberFormatException.class);

但是,如果你正在使用JUnit的旧版本,或者如果你想要做的多个“例外”的断言在同样的测试方法,那么标准的成语是:

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

这是一个很好的习惯用法,当你想测试异常的情况时,比如它的消息,而不仅仅是它的存在。 – Yishai 2010-10-28 22:02:29

+0

+1 - 关于旧版本的好处。 – Feanor 2010-10-28 22:02:55

+0

+1 - 如果没有第二个例子,这个问题的答案就不完整。在实践中,由于上述原因,我需要更多地默认这种方法。 – Synesso 2010-10-28 22:20:28

2

使用@Test(预期= IOException.class)

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

这是好的,如果你有一个预期的例外。另一种策略是在测试方法的最后添加一个Assert.fail()。如果不引发异常,则测试将相应地失败。例如

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

假设你正在使用JUnit 4,调用该方法在测试中,导致它抛出异常的方式,和使用JUnit注释

@Test(expected = NumberFormatException.class) 

如果引发异常,测试会通过。

+1

+1 - Fast,boy。 – duffymo 2010-10-28 21:59:49

+0

@duffymo:Thanks!:) – Feanor 2010-10-28 22:00:49

3

You can do this

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

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

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

如果你可以使用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)要好得多,因为如果IndexOutOfBoundsException之前foo.doStuff()

this article抛出的测试将失败和the ExpectedException JavaDoc的详细信息

+0

For深入推理和解释我想推荐这篇文章:http://monkeyisland.pl/2010/07/26/expected-exception-in-tests/ 从我+1。 – 2010-10-29 03:46:24

+0

+1 - 我不知道这存在。 – 2013-01-22 12:43:32

+0

@JonathanDrapeau修复了这个链接。谢谢你让我知道! – NamshubWriter 2014-09-21 16:57:44

0

解决方案,我不受特定的JUnit版本约束,由catch-exception提供,用于克服JUnit机制固有的一些缺点。