JUnit:如果捕获到异常,则成功进行测试

use*_*231 4 junit exception

如果JUnit测试返回预期的异常,是否有可能成功?

你能告诉我如何通过简化的例子来实现这样的测试吗?

非常感谢.

Hri*_*esh 6

为什么你不能在测试中捕获你的异常?有不同的方法可以做到这一点.像注释一样@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);
     }
 }
Run Code Online (Sandbox Code Playgroud)

使用这种方法有几个好处.

  • 如果您有自定义异常,并带有错误代码,则可以声明错误代码.从而收紧你的测试用例.
  • 相同类型但具有不同错误代码的任何其他意外异常都将无法通过测试.(这有助于您在持续开发中并且团队不断重构代码以满足新的需求.测试可以捕获它.)