我的测试:这是在萨克斯之后强调内容的地方。并坚持我有一个 try-catch block ....但是互联网上说测试异常的正确方法是 @Test(expected=IllegalArgumentException.class)
@Test(expected= XMLClientNotFoind.class)
public void testGetClientFromIP() throws XMLClientNotFound{
...
assertEquals(c, sax.getClientFromIP("101.0.2.01"));
}
getClientFromIP 方法在这里:
public Client getClientFromIP(String ip) throws XMLClientNotFound {
...
throw new XMLClientNotFound();
}
我的异常(exception)是:
public class XMLClientNotFound extends Exception{
}
最佳答案
首先:
@Test(expected=IllegalArgumentException.class)
不应被视为一种正确的方法,尤其是在存在此类通用异常的情况下。原因是您无法控制测试方法中的哪个语句实际引发了异常。此外,您不能对消息标签、原因等做出任何断言。
使用 try-catch
准确地包围假设抛出异常的行是正确的方法:
try {
shouldThrow()
fail("Expected exception");
} catch(XMLClientNotFound e) {
assertThat(e).hasMessage("Expected message"); //FEST-Assert syntax
}
您也可以尝试我 wrote 中的 JUnit @Rule
前一段时间让你的测试更具可读性。
关于Java:Junit4:异常测试不起作用,坚持使用 try-catch block :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4937938/