The following Calculator
class has a divide
method that should throw an exception if denominator
is equal to zero.
public class Calculator {
public static int sum(int value1, int value2) {
return value1 + value2;
}
public static int multiply(int value1, int value2) {
return value1 * value2;
}
public static int divide(int numerator, int denominator) {
return numerator / denominator;
}
}
We can verify that behavior via the assertThrows
method, as shown below.
@Test
void divisionByZeroThrowsException() {
assertThrows(ArithmeticException.class, () -> {
Calculator.divide(1, 0);
});
}
Note that:
assertThrows
is the exception type you expect to be thrown.Write test methods that verify if the get
method of ArrayList
throws an IndexOutOfBoundsException
when passing an index out of range (index < 0
or index >= size()
).
-1
on an non-empty list.0
on an empty list.1
on a list with a single element.5
on a list with 5 elements.0
of a non-empty list does not
throw an exception using the method assertDoesNotThrow
.