引发了“将引发预期的异常,但一无所获”导致我的测试用例失败。如何解决这个问题。如果查找阶乘时数字为负,我想抛出一个异常,

测试文件:

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


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

最佳答案

您的测试很好,问题出在您的代码没有引发异常,或更正确地说,引发并捕获了异常。

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

关于java - Java Junit-会引发预期的异常,但不会引发任何异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58035410/

10-09 15:50