Skip to main content
 首页 » 编程设计

exception之JUnit : a Successful test if an exception is catched

2024年11月01日57lovecherry

如果 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); 
     } 
 } 

使用这种方法有几个好处。
  • 如果您有自定义异常,带有错误代码,您可以
    断言错误代码。从而收紧您的测试用例。
  • 任何其他相同类型但不同错误的意外异常
    代码将无法通过测试。 (当您处于连续状态时,这会有所帮助
    开发和团队不断重构代码以更新
    要求。测试捕获了它。)