Test for Exception in JUnit 5 and JUnit 4

In this tutorial you will learn how to write a JUnit Test that validates if method under the test throws correct exception. This tutorial will have examples for JUnit 5 and JUnit 4 as well.

Let’s begin with JUnit 5 version first.

JUnit 5. “assertThrows()” Assertion

To test for exception in JUnit 5 we use the assertThrows() assertion.

Let’s assume that we need to validate if our method under test throws ArithmeticException.  To assert that our method under test throws ArithmeticException, we can use the assertThrows() assertion the following way:

@Test
@DisplayName("Division by zero")
void testIntegerDivision_WhenDividendIsDividedByZero_ShouldThrowArithmeticException() {
   
    // Arrange
    int dividend = 4;
    int divisor = 0;
    String expectedExceptionMessage = "/ by zero";

    // Act & Assert
    ArithmeticException actualException = assertThrows(ArithmeticException.class, ()->{
       // Act
        calculator.integerDivision(dividend, divisor);
    }, "Division by zero should have thrown an Arithmetic exception.");

    // Assert
    assertEquals(expectedExceptionMessage, actualException.getMessage(),
            "Unexpected exception message");

}

Junit 5 and 4. Using the Try and Catch.

When using the Try and Catch approach, you will need to catch the exception you are expecting first and then, inside of the catch{} block assert that the exception object is of the type you are expecting or its getMessage() method contains the message you are expecting.

Also, you will need to add the call to fail() inside of the try{} block. This is needed to make sure the test fails if the code does not throw an Exception your expect.

@Test
public void testWithTryAndCatchNullPointerException() {
    String name = getName();
    try {
        System.out.println(name.length());
        fail();
    } catch (NullPointerException ex) {
        assertTrue(ex instanceof NullPointerException);
    }
}

JUnit 4. Using @Test Expected Attribute

One way to test for expected exceptions is to use the @Test’s expected attribute to specify that the method below should throw an exception specified by the attribute. For example:

@Test( expected = NullPointerException.class )

I have created a very simple method that if run should throw a NullPointerException and the line above with the @Test( expected = ) attribute will make the test case pass.

package myunittests;

import org.junit.Test;

 
public class ExpectingExceptionTest {
    
    @Test(expected = NullPointerException.class)
    public void testNullPointerException()
    {
        String name = getName();
        System.out.println(name.length());
    }
    
    private String getName()
    {
        return null;
    }
}

JUnit 4. Using the @Rule ExpectedException

With the @Rule annotation we will first need to declare the ExpectedException and annotate it with @Rule. Inside of the Test method we will then simply need to specify the Exception we are expecting this method to throw using the expect() method of the ExpectedException object.

package myunittests;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

 
public class ExpectingExceptionTest {
    
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    
    @Test 
    public void testUsingTheRuleNullPointerException()
    {
        thrown.expect(NullPointerException.class);
        String name = getName();
        System.out.println(name.length());
    }

    private String getName() {
        return null;
    }
}

Hope that this short blog post was helpful to you. If you are interested to learn more about how to test Java with JUnit and Mockito, please have a look at my video course below.

Leave a Reply

Your email address will not be published. Required fields are marked *