“期望抛出异常,但没有抛出任何异常”,这会导致我的测试用例失败。如何解决这个问题。我想要抛出一个异常,如果在查找阶乘时数字为负数,
测试文件:
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);
}
}我希望输出是成功的,但它却导致了失败
发布于 2019-09-21 05:52:58
你的测试很好,问题在于你的代码没有抛出异常,或者更准确地说-抛出并捕获了它。
从方法中删除catch (OutOfRangeException e)子句并添加throws OutOfRangeException,然后您的测试将通过
发布于 2019-09-21 06:04:21
当你的方法抛出异常时,你可以有一个类似下面的测试用例。
@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";
}
}https://stackoverflow.com/questions/58035410
复制相似问题