Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Assert Exceptions in JUnit

In JUnit 4, we can test whether a method throws an exception by using the expected attribute of the @Test annotation. We can use the Assertions.assertThrows() to test the same thing in JUnit 5.

In this tutorial, we will learn how to check whether an exception occurs using JUnit.

JUnit 4 Expected Exception

We can use the expected attribute with the @Test annotation to define the exception we expect from the test method. If the exception occurs in the test method, then the test passes.

The test fails if the expected exception does not take place. Let's take a look at both these scenarios.

In the following code, we are expecting an ArrayIndexOutOfBounds exception. The exception occurs when we try to access the element at index 100 of an array of size 5. The test will pass in this case.

import org.junit.Test;

public class Demo
{
	@Test(expected = ArrayIndexOutOfBoundsException.class)
	public void testMethod()
	{
	    int[] intArr = {10, 20, 30, 40, 50};
	    int x = intArr[100];//Exception	
	}
}

Now, if we try to access the element at index 2, then no error occurs. In this case, the test will fail as we were expecting an exception.

import org.junit.Test;

public class Demo
{
	@Test(expected = ArrayIndexOutOfBoundsException.class)
	public void testMethod()
	{
	    int[] intArr = {10, 20, 30, 40, 50};
	    int x = intArr[2];	
	}
}

Failure Trace:


java.lang.AssertionError: Expected exception: java.lang.ArrayIndexOutOfBoundsException

If we need to verify some additional properties of the exception, then we can use the ExpectedException rule. Let's create a method that throws an ArrayIndexOutOfBounds exception with an "Out of Bounds" exception message. Let's try to verify this message by using an ExpectedException rule.

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class Demo
{
	@Rule
	public ExpectedException rule = ExpectedException.none();
	
	void someMethod() throws ArrayIndexOutOfBoundsException
	{
		throw new ArrayIndexOutOfBoundsException("Out Of Bounds");
	}
	
	@Test
	public void testMethod()
	{
		rule.expect(ArrayIndexOutOfBoundsException.class);
		rule.expectMessage("Out Of Bounds");
	    someMethod();
	}
}

JUnit 5 Expected Exception

JUnit 5 introduced the Assertions API that we can use to test the exception thrown by a method. We will use Assertions.assertThrows() method for asserting exceptions.

This method takes the expected exception class and an executable code block or lambda expression as parameters. If the expected exception occurs, then the test will pass. If no exception occurs, or an exception of some other type occurs, then the test fails.

In the code below, we are expecting a NumberFormatException when we try to parse a string.

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class Demo
{
	@Test
	void testExpectedException()
	{
		Assertions.assertThrows(NumberFormatException.class, () -> {
	    Integer.parseInt("Twenty");//Exception
	  });
	}
}

The assertThrows() method can expect parent class exceptions as well. So if we pass the Exception class as the first parameter, then the test will succeed for any exception(as all exceptions extend the Exception class).

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class Demo
{
	@Test
	void testExpectedException()
	{
		Assertions.assertThrows(Exception.class,//Parent Class Exception
                                () -> {Integer.parseInt("Twenty");}
                                );
	}
}

The assertThrows() method returns an Exception object. We can use it to verify additional properties of the exception thrown.

Let's try to verify the exception message using assertEquals().

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class Demo
{
	@Test
	void testExpectedException()
	{
		Exception e = Assertions.assertThrows(NumberFormatException.class, () -> {
	    Integer.parseInt("Twenty");//Exception
	  });
		
		String msg = e.getMessage();
		assertEquals("For input string", msg);
	}
}

Summary

In this tutorial, we learned how to assert whether an exception was thrown or not using JUnit. For JUnit 4, we can use the expected attribute with the @Test annotation. If we want to verify other exception properties, then we can use the ExpectedException rule. For JUnit 5, we can use the Assertions.assertThrows() method.