【发布时间】:2015-08-04 18:35:02
【问题描述】:
我正在使用 JUnit 4.11。
Eclipse 版本:Luna Service Release 2 (4.4.2)
我需要做异常测试。代码可能是这样的:
// src code
public void myMethod throws MyException {
...
throw new MyException(msg);
...
}
// test code
@Test (expected = MyException.class)
public void testMyMethod() {
try {
myMethod();
fail();
} catch (MyException e) {
assertEquals(expectedStr, e.getMessage());
}
}
但是测试总是失败,我哪里错了?
【问题讨论】:
-
补充@rgettman 的(正确)答案:您应该使用JUnit 的
ExpectedException测试异常。