2013-03-05 216 views
70

我真的很陌生。JUnit测试例外

我正在构造函数上运行一些JUnit测试。构造函数是这样的,如果给它的一个参数赋予一个null或一个空字符串,它应该会抛出一个异常。

当我在JUnit中用一个空或空字符串参数测试这个构造函数时,我得到一个红色的条,即使我几乎100%确定构造函数方法在传入这些参数时确实会抛出一个异常到它。

如果该方法抛出异常的方式应该不会出现JUnit中的绿色条?或者,当抛出异常的方式按照它应该的方式工作时,你应该得到一个红色的条?

回答

108
@Test(expected = Exception.class) 

告诉Junit异常是预期的结果,因此当引发异常时测试将被传递(标记为绿色)。

对于

@Test 

为失败,如果抛出异常JUnit会考虑测试。
This link may help。

38

你确定你告诉它期待异常吗?

较新的JUnit(> = 4.7),你可以使用类似(从here

@Rule 
public ExpectedException exception = ExpectedException.none(); 

@Test 
public void testRodneCisloRok(){ 
    exception.expect(IllegalArgumentException.class); 
    exception.expectMessage("error1"); 
    new RodneCislo("891415",dopocitej("891415")); 
} 

,并为老年人junit的做法是:

​​
+0

如果测试类引发异常,则可以简单地引发异常并测试已写入Junit测试用例的位置。使用@Test(expected = IllegalArgumentException.class) – 2015-11-03 07:20:44

5

如果你的构造函数与此类似一个:

public Example(String example) { 
    if (example == null) { 
     throw new NullPointerException(); 
    } 
    //do fun things with valid example here 
} 

然后,当你运行这个JUnit测试时,你会得到一个绿色的条:

@Test(expected = NullPointerException.class) 
public void constructorShouldThrowNullPointerException() { 
    Example example = new Example(null); 
} 
6

使用ExpectedException Rule(版本4.7)的一个优点是您可以测试异常消息,而不仅仅是预期的异常。

而且使用匹配器,你可以测试消息的一部分,你有兴趣:

exception.expectMessage(containsString("income: -1000.0")); 
4

虽然@Test(expected = MyException.class)ExpectedException rule是非常不错的选择,也有一些情况,其中JUnit3风格异常捕获仍是最好的路要走:

@Test public void yourTest() { 
    try { 
    systemUnderTest.doStuff(); 
    fail("MyException expected."); 
    } catch (MyException expected) { 

    // Though the ExpectedException rule lets you write matchers about 
    // exceptions, it is sometimes useful to inspect the object directly. 

    assertEquals(1301, expected.getMyErrorCode()); 
    } 

    // In both @Test(expected=...) and ExpectedException code, the 
    // exception-throwing line will be the last executed line, because Java will 
    // still traverse the call stack until it reaches a try block--which will be 
    // inside the JUnit framework in those cases. The only way to prevent this 
    // behavior is to use your own try block. 

    // This is especially useful to test the state of the system after the 
    // exception is caught. 

    assertTrue(systemUnderTest.isInErrorState()); 
} 

另一个声称在这里帮助的图书馆是catch-exception;然而,截至2014年5月,该项目似乎处于维护模式(由Java 8废弃),很像Mockito catch-exception只能操作非final方法。