Java 如何为预期的异常测试方法添加多个案例?

Java 如何为预期的异常测试方法添加多个案例?,java,exception,junit4,Java,Exception,Junit4,我正在一个学校项目中工作,该项目要求我测试自定义的异常 有5个Calculator.java文件,我的工作是添加更多的案例,并找到运行完全正确的案例 然而,当我尝试使用预期异常测试来测试异常时,似乎只要第一个案例运行良好,程序就会自动抛出并停止。//TODO后面的其他案例根本不会运行 /** * The calculate method have to return the Grade based on : * * "lab", "ass1" and "ass2" marks are

我正在一个学校项目中工作,该项目要求我测试自定义的异常

有5个Calculator.java文件,我的工作是添加更多的案例,并找到运行完全正确的案例

然而,当我尝试使用预期异常测试来测试异常时,似乎只要第一个案例运行良好,程序就会自动抛出并停止。//TODO后面的其他案例根本不会运行

 /**
 * The calculate method have to return the Grade based on :
 * 
 * "lab", "ass1" and "ass2" marks are between 0 and 10 (inclusive).
 * + "final" is between 0 and 100 (inclusive).
 * 
 * If any of these components are not within the expected range 
 * then an OutOfRangeException is thrown.
 *  
 */
//Here is the interface of MarkCalculator
public interface Calculator {
    Grade calculate(int lab, int ass1, int ass2, 
                            int final, boolean attended) throws OutOfRangeException; 
}

有人能告诉我如何防止这种情况发生吗,谢谢

@Test(expected = OutOfRangeException.class)
public void testException() throws OutOfRangeException {
    calculator.calculateMark(-1, 0, 0, 0, true);
    //TODO: write more test cases if you need


    calculator.calculateMark(100 , 0 , 0 , 0 , true);
    calculator.calculateMark(0 , 11 , 0 , 0 , true)
}

更简单的方法是将计算提取到测试类本身的另一个方法

private Class cauculate(int lab, int assignment1, int assignment2, int finalexam, boolean attendedFinal){
    try{
        calculator.calculateMark(lab, assignment1, assignment2, finalexam, attendedFinal);
    } catch (Exception e){
        return e.getClass();
    }
    return Void.class;
}

@Test
public void testException() {
    Assert.assertEquals(ComponentOutOfRangeException.class, calculate(-1, 0, 0, 0, true));
    Assert.assertEquals(ComponentOutOfRangeException.class, calculate(11, 0, 0, 0, true));
//....
}

单元测试的目的是测试一个特定的东西,这就是为什么它不支持对多个异常的冷处理(因为java本身在没有try-catch或其他处理的情况下忽略异常是无效的),这就是为什么您需要一个解决方法,正如前面的答案所建议的那样

我的建议是编写不同的@test函数,并根据它们所测试的内容对每个函数进行命名(例如test_firstParameterNull、test_secondParameterNull等)。这样,当您最终运行测试时,他们将能够提供关于失败原因的反馈,而不是一般的“您的计算器失败”。 公平地说,您的单元测试将如下所示。每个场景中只有1个x会改变,所以您可以复制粘贴任意次数,并测试非常特定的案例

@Test(预期=ComponentOutOfRangeException.class)
公共无效测试异常(){
计算器。计算器标记(x,x,x,x,x);
}

检查这里。。。特别是带有
的部分,请尝试。。。catch
块。如果你想使用注释,你必须将每个应该失败的调用放入它自己的测试方法中。因为当异常发生时,方法的其余部分将不再执行。