我想知道是否可以测试(使用JUnit)由异常生成的特定消息被抛出而不仅仅是“是否抛出异常”。 例如,JunitTest.java代码实际上会通过测试,因为抛出了异常,但是如果我还想测试由异常生成的字符串等于:“测试异常:整数可能不是负数..”这可能吗?JUnit:测试某种类型的异常
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);
}
}
的[?在Java中我怎么能验证使用JUnit抛出的异常]可能重复(http://stackoverflow.com/questions/785618/in- java-how-can-i-validate-a-thrown-exception-with-junit) – artbristol 2012-04-13 12:14:44
@artbristol答案似乎是使用老版本的JUnit(不需要'expected = ...'注解)。 – assylias 2012-04-13 12:18:52