AssertThrows example

In this post under Junit 5, I will show with example what is the purpose of and how to use AssertThrows feature.

AssertThrows method checks whether the called method throws the user specified exception or not. If the user specified exception is thrown, the test passes otherwise the test fails.

For our example, we will use the below Calculator class for testing purposes.


package package3;

public class Calculator {
    private int x, y;

    public int add() {
        return x + y;

    public int sub() {
        return x - y;

    public int divide() {
        return x/y;

    public int getX() {
        return x;

    public void setX(int x) {
        this.x = x;

    public int getY() {
        return y;

    public void setY(int y) {
        this.y = y;

The Calculator class has methods to set X and Y variable. It also has methods to perform addition, substraction, and division using X and Y.

Below is the test class


1  package package3;
3  import static org.junit.jupiter.api.Assertions.assertThrows;
5  import org.junit.jupiter.api.Test;
7  class CalculatorTest {
9      private Calculator calculator = new Calculator();
11     @Test
12     void testAdd() {
13         calculator.setX(5);
14         calculator.setY(0);
16         assertThrows(ArithmeticException.class, () -> calculator.divide());
17     }
18 }

In the above code, at line 9 we create an instance of “Calculator” class.

At line 13 and 14, we set X and Y variables of “Calculator” instance to 5 and 0.

At line 16, we are calling “assertThrows” method passing two arguments.

The first argument is the type of exception that you are expecting the called code will throw. In this case the called code is “calculator.divide()”.

The second argument passes a lambda implementation of “Executable” interface. In this implementation we are calling the test code i.e., “calculator.divide”.

So in this case the divide operation will throw ArithmeticException exception and the test passes because that’s what we had expected.

Leave a Reply