Java Junit-会引发预期的异常,但不会引发任何异常

时间:2019-09-20 21:33:06

标签: java exception junit

抛出“预期的异常但没有任何反应”,导致我的测试用例失败。如何解决这个问题。如果要查找阶乘,如果数字为负,我想抛出一个异常,

测试文件:

public void testCalculateFactorialWithOutOfRangeException(){

  Factorial factorial = new Factorial();
    assertThrows(OutOfRangeException.class,
     () -> factorial.calculateFactorial(-12));

}

代码文件:

public class Factorial {
    public String calculateFactorial(int number) {
        //If the number is less than 1
        try {
            if (number < 1)
                throw new OutOfRangeException("Number cannot be less than 1");
            if (number > 1000)
                throw new OutOfRangeException("Number cannot be greater than 1000");

        } catch (OutOfRangeException e) {

        }
    }
}

public class OutOfRangeException extends Exception {
    public OutOfRangeException(String str) {
        super(str);
    }
}

我希望输出会成功,但是会导致失败

2 个答案:

答案 0 :(得分:3)

您的测试很好,问题出在您的代码中,它不会引发异常,或更准确地说,不会引发并捕获异常。

从方法中删除catch (OutOfRangeException e)子句并添加throws OutOfRangeException,然后测试将通过

答案 1 :(得分:1)

当您的方法引发异常时,您可以具有如下所示的测试用例。

@Test(expected =OutOfRangeException.class)
public void testCalculateFactorialWithOutOfRangeException() throws OutOfRangeException{

    Factorial factorial = new Factorial();
   factorial.calculateFactorial(-12);
}

但是,在您的情况下,您不是在类中引发异常,而是在catch块中处理该异常,如果您在方法中引发异常,则它将起作用。

class Factorial {

    public String calculateFactorial(int number) throws OutOfRangeException{

        //If the number is less than 1

        if(number < 1)
            throw new OutOfRangeException("Number cannot be less than 1");
        if(number > 1000)
            throw new OutOfRangeException("Number cannot be greater than 1000");


        return "test";
   }
}