Reputation: 65
"Expected exception to be thrown but nothing" is thrown causing a failure in my test case. How to resolve this. I want to throw an exception if the number is negative while finding a factorial,
Test File:
public void testCalculateFactorialWithOutOfRangeException(){
Factorial factorial = new Factorial();
assertThrows(OutOfRangeException.class,
() -> factorial.calculateFactorial(-12));
}
Code file:
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);
}
}
I expected the output to be a success but it is causing a failure
Upvotes: 3
Views: 34256
Reputation: 919
You can have a test case like below when your method throws an exception.
@Test(expected =OutOfRangeException.class)
public void testCalculateFactorialWithOutOfRangeException() throws OutOfRangeException{
Factorial factorial = new Factorial();
factorial.calculateFactorial(-12);
}
However in your case, you are not throwing an exception in class but it is handled in the catch block, if you throw an exception in your method then it will work.
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";
}
}
Upvotes: 3
Reputation: 12953
Your test is fine, the problem is with your code that does not throw the exception, or more correctly- throws and catches it.
Remove the catch (OutOfRangeException e)
clause from the method and add throws OutOfRangeException
and then your test will pass
Upvotes: 10