IT序号网

exception之Junit 异常处理

shangdawei 2025年05月04日 编程语言 263 0

我想知道这个测试用例是应该通过还是失败 因为 预期 = IndexOutOfBoundsException.class 实际上它抛出了算术异常。谁能解释一下?

@Test(expected = IndexOutOfBoundsException.class) 
public void testDivideNumbers()throws ArithmeticException{ 
    try{ 
        double a = 10/0; 
        fail("Failed: Should get an Arithmatic Exception");  
 
        } 
    catch (ArithmeticException e) { 
 
        }    
 
} 

请您参考如下方法:

要测试是否抛出了正确的异常,您不应该让测试方法抛出异常,而应该让测试本身导致抛出的异常。

所以如果 ArithmeticException 是预期的那么测试应该是:

@Test(expected = ArithmeticException.class) 
public void testDivideNumbers() { 
     double a = 10/0; 
} 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!