Junit Expected Exception Testcases Example

Junit is a unit testing framework for the Java programming language. If you want to read about best practices followed for junit testing then here is an excellent guide for your reference.

In this post, I am writing a sample test case which expects exceptions to be thrown on runtime. If it gets the expected exception, test passes. If expected exception is not detected, test cases fails.

These type of test cases are very useful where you want your application to fail for very absurd input.

package com.howtodoinjava.test.junit;

import org.junit.Test;

public class ExpectedExceptionTest
{
	//This test case fails because it was expecting ArithmeticException
	@Test(expected = ArithmeticException.class)
	public void expectArithmeticException()
	{
		System.out.println("Everything was fine here !!");
	}

	//This test case fails because it was expecting ArithmeticException
	@Test(expected = ArithmeticException.class)
	public void expectArithmeticException2()
	{
		throw new NullPointerException();
	}

	//This test case passes because it was expecting NullPointerException
	@Test(expected = NullPointerException.class)
	public void expectNullPointerException()
	{
		//some code which throw NullPointerException in run time
		throw new NullPointerException();
	}
}

In above 3 testcases, first two fails because they were expecting ArithmeticException which they didn’t get while test case execution.

Third testcase gets pass because, it was expecting the NullPointerException and testcase threw it.

This way you can write your testcases which are dependent on some exceptions to test the behavior of application on failure.

Happy Learning !!

4 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.