When writing JUnit, at times you would want to check methods for exceptions. Here’s how you do it.
In below method, we divide 2 numbers and throw error if second argument of method is zero.
public static double div(double x, double y) { if(y == 0) { throw new ArithmeticException("divide by zero"); } return (double)(x/y); }
We would want to check scenario in test case where we assert Arithmetic exception is one thrown when passed 0 as second argument.
Your test method looks like this.
@Test
void should_return_exception_when_given_value_zero() {
//given
double x = 5;
double y = 0;
//when
Executable executable = () -> SimpleClass.div(x, y);
//then
assertThrows(ArithmeticException.class, executable);
}
Note, we are using Executable instance and lambda to execute our method in “when” section. This is because directly executing method which throws exception will halt java program from execution.
Executable instance helps hold exception and let it compare with exception we expect in “then” section.
Leave a Reply