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

我期望输出是成功的,但它导致了失败

你的测试很好,问题出在你的代码上,它没有抛出异常,或者更准确地说 - 抛出并捕获它。

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

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

@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";
}
}

相关内容

最新更新