【发布时间】:2012-04-25 19:10:45
【问题描述】:
我想知道我是否可以测试(使用 JUnit)由异常生成的特定消息被抛出,而不仅仅是“是否”抛出异常。 例如,JunitTest.java 代码实际上会通过测试,因为抛出了异常,但如果我还想测试异常生成的字符串是否等于:“Test Exception: Integer may not be negative..” 这可能吗?
TestException.java
public class TestException extends Exception {
/**
* @param message informative message about the problem found
*/
public TestException (String message) {
super("Test Exception: " + message);
}
}
Test.java
public void function(Integer mustBePositive) throws TestException {
if (mustBePositive < 0) {
throw new TestException("Integer may not be negative..");
}
else {
mustBePositive = myNum
}
}
JunitTest.java
import org.junit.*;
public class JUnitTest {
@Test(expected = TestException.class)
public void functionTest() throws TestException {
function(-1);
}
}
【问题讨论】:
-
@artbristol 答案似乎使用的是旧版本的 JUnit(没有
expected=...注释)。
标签: java unit-testing exception junit