Expected Exception Test in JUnit 4

In my previous article I have written down the sample code for Junit 4 testing using annotations. In this tutorial I would like to write about expected exception testing and Rules which is introduced from JUnit 4.7. JUnit 4 introduced the expected parameter, which makes a test succeed if and only if a certain exception is thrown. In some scenarios programmers has to test the custom exceptions which are expected if a condition failes. So, testing exception also become more important for the JUnit testing.

With JUnit 4.7, it introduced @Rules annotations for defining the expected exception object for the class level and then it will be used inside all the methods. One advantage of using this is that you can check the expected message from the exception. Another traditional approach is to use @Test(expected = NullPointerException.class) syntax on each method. Look at the below example.

package javabeat.net.junit;

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

public class JUnitExceptionTest {
	@Rule public ExpectedException exception = ExpectedException.none();

	@Test(expected = NullPointerException.class)
	public void nullPointerExceptionTest() {
		String testStr = null;

	public void expectedExceptionTest() {
		String testStr = null;

Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!