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;
		testStr.toString();
	}

	@Test
	public void expectedExceptionTest() {
		exception.expect(NullPointerException.class);
                exception.expectMessage("Message");
		String testStr = null;
		testStr.toString();
	}
}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. comments on JUNIT: Please, Need little more descriptions and explanations line by line code wise as comments which helps new developers to understand easily without any doubts happened while learning. Expecting your needful help in this regard. Thanks to all

Speak Your Mind

*