JUnit测试 - 分析预期的异常

Far*_*rid 41 java junit exception

在JUnit中,我目前正在使用注释来期待我的测试中的异常.

有没有办法分析这个例外?例如,我期待a CriticalServerException,但我也想验证getMessage方法的内容.

Fil*_*ale 68

如果您有JUnit 4.7或更高版本,请尝试ExpectedException

这个问题有一个例子,复制如下:

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

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

  • 感谢@Progman提供此问题的链接. (2认同)

Pro*_*man 21

我不确定你是否应该这样做.使用try-catch块来检查错误消息是如此junit3ish.我们现在有这个很酷的功能,您可以编写@Test(expected=CriticalServerException.class)并且您想要"返回"并再次使用try-catch来获取您期望的异常,仅用于检查错误消息?

IMO你应该留下@Test(expected=CriticalServerException.class)注释并忽略错误信息.检查错误消息,可以更改,因为它是一个更"人类可读"的字符串而不是技术值,也可能是棘手的.您强制异常具有特定的错误消息,但您可能不知道是谁生成了异常以及他选择了什么错误消息.

通常,您希望测试方法是否抛出异常,而不是实际的错误消息.如果错误消息非常重要,您应该考虑使用它抛出的异常的子类并将其检入@Test(expected=...).


Jig*_*shi 12

try{ 
    //your code expecting to throw an exception
    fail("Failed to assert :No exception thrown");
} catch(CriticalServerException ex){
    assertNotNull("Failed to assert", ex.getMessage()) 
    assertEquals("Failed to assert", "Expected Message", ex.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

  • 这是使用JUnit 3的正确方法.使用JUnit 4(<4.7)遵循Progman的建议.使用JUnit 4.7及更高版本,请遵循Filippo的建议. (3认同)