如果 JUnit 测试返回预期的异常,它是否有可能成功?
你能通过一个简化的例子告诉我如何实现这样的测试吗?
非常感谢。
请您参考如下方法:
为什么你不能在测试中捕捉你的异常?有不同的方法可以做到这一点。喜欢批注@Test(expected = DataAccessException.class)
这也需要根据具体情况使用。但下面的方式是我建议的。
public class TestCase{
@Test
public void method1_test_expectException () {
try{
// invoke the method under test...
Assert.fail("Should have thrown an exception");
// This above line would only be reached if it doesnt throw an exception thus failing your test.
}
catch(<your expected exception> e){
Assert.assertEquals(e.getcode(), somce error code);
}
}
使用这种方法有几个好处。
断言错误代码。从而收紧您的测试用例。
代码将无法通过测试。 (当您处于连续状态时,这会有所帮助
开发和团队不断重构代码以更新
要求。测试捕获了它。)