JUnit Expected Exception Test: @Test(expected)

JUnit provides the facility to trace the exception and also to check whether the code is throwing expected exception or not.

Junit4 provides an easy and readable way for exception testing, you can use

While Testing exception, you need to ensure that exception class you are providing in that optional parameter of @test annotation is the same. This is because you are expecting an exception from the method you are Unit Testing, otherwise our JUnit test would fail.

Example@Test(expected=IllegalArgumentException.class)

By using "expected" parameter, you can specify the exception name our test may throw. In above example, you are using "IllegalArgumentException" which will be thrown by the test if a developer uses an argument which is not permitted.

Example using @test(expected)

Let's understand exception testing by creating a Java class with a method throwing an exception. You will handle it and test it in a test class. Consider JUnitMessage.java having a method which simply do a mathematical operation based on input received by the user. If any illegal argument would be entered, it will throw "ArithmeticException". See below:

JUnit Exception Test

package gtupapers.junit;

public class JUnitMessage{

	private String message;

	public JUnitMessage(String message) {
		this.message = message;
	}

public void printMessage(){

	System.out.println(message); 
	int divide=1/0;

}

public String printHiMessage(){ 

	message="Hi!" + message;
	
	System.out.println(message);

	return message;
}

}

Code Explanation:

Let's create a test class for above java class to verify exception.

See below test class to unit test exception (ArithmeticException here) throwing from above java class:

AirthematicTest.java

JUnit Exception Test

package gtupapers.junit;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class AirthematicTest {

	public String message = "Saurabh";
	
	JUnitMessage junitMessage = new JUnitMessage(message);
	
	@Test(expected = ArithmeticException.class)
	public void testJUnitMessage(){

		System.out.println("Junit Message is printing ");
		junitMessage.printMessage();

	}

	@Test
	public void testJUnitHiMessage(){ 
		message="Hi!" + message;
		System.out.println("Junit Message is printing ");
		assertEquals(message, junitMessage.printMessage());
	
	}
}

Code Explanation:

If you execute this test class, the test method is executed with each defined parameter. In the above example, the test method is executed five times.

Let's execute it and verify the result. See below the test runner class to execute JunitTestExample.java

Output:

Here is the output which shows successful test with no failure trace as given below:

JUnit Exception Test

Summary:

 

YOU MIGHT LIKE: