Aka*_*ash 1 java junit exception
抛出“预期的异常但什么都没有”导致我的测试用例失败。如何解决这个问题。如果在查找阶乘时数字为负,我想抛出异常,
测试文件:
public void testCalculateFactorialWithOutOfRangeException(){
Factorial factorial = new Factorial();
assertThrows(OutOfRangeException.class,
() -> factorial.calculateFactorial(-12));
}
Run Code Online (Sandbox Code Playgroud)
代码文件:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我预计输出会成功,但它导致了失败
您的测试很好,问题在于您的代码没有抛出异常,或者更正确的是抛出并捕获它。
catch (OutOfRangeException e)从方法中删除子句并添加throws OutOfRangeException,然后您的测试将通过
| 归档时间: |
|
| 查看次数: |
3594 次 |
| 最近记录: |