Junit's annotation based expected exception testing

Junit provides an option of tracing exception thrown by a Java method. There are different ways of handling exceptions in JUnit tests. Standard Junit’s org.junit.Test annotation offers expected attribute that allows us specifying the a Throwable to cause a test method to succeed if an exception of the specified class is thrown by the method. A Java unit test should verify correct exception thrown in exceptional case and no exception should be thrown in normal case. For this to test exception thrown by a Java method using @Test(expected=””) we need to use at least Junit 4.7. One of the many situations where we need to test exception thrown by a Java method is testing an API method that should throw IllegalArgumentException if arguments passed to the method are not matching to pre-conditions. For example, in order to test that we need to use @Test(expected=IllegalArgumentException.class) annotation. We can replace IllegalArgumentException.class with any other exception e.g. NullPointerException.class or ArithmeticException.class etc as per the requirment. In order to test any Java method for throwing excpetion, we need to ensure that arguments provided to the method, from the test must result in expected Exception, otherwise JUnit test will fail.

The following configurations are required in order to run the application
Eclipse Kepler
JDK 1.8
Have maven installed and configured
Junit dependency in pom.xml
Now we will see the below steps how to create a maven based spring project in Eclipse
Step 1. Create a standalone maven project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

Now enter the required fields (Group Id, Artifact Id) as shown below
Group Id : com.roytuts
Artifact Id : java
Step 2. Modify the pom.xml file as shown below.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <!-- junit -->

Step 3. Here is an example of how to test exception thrown by a method called secsToMins(), which returns minutes as seconds/60, but before calculating minutes for given seconds it checkes whether minutes are positive or not, and if minutes are zero or negtaive it throws IllegalArgumentException.

package com.roytuts.junit.exception;
public class SecondsToMinutesUtils {
    public int secsToMins(int seconds) {
        if (seconds <= 0) {
            throw new IllegalArgumentException("seconds (" + seconds + ") cannot be 0 or negative");
        return seconds / 60;

Step 4. Below is the example for Exception testing, we can see that our testSecsToMins() method is annotated with @Test(expected=IllegalArgumentException.class), which means it expect an illegalArgumentException, when we run this JUnit test.

package com.roytuts.junit.exception;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class SecondsToMinutesUtilsExceptionTest {
    private SecondsToMinutesUtils secsToMins;
    public void setUp() throws Exception {
        secsToMins = new SecondsToMinutesUtils();
    @Test(expected = IllegalArgumentException.class)
    public void testSecsToMins() {
        int seconds = 0;
        int expResult = 0;
        int result = secsToMins.secsToMins(seconds); // should throw exception
        assertEquals(expResult, result);

Step 5. Now if you run the test class test will be passed with current arguments, but if we change arguments, the test will be failed like below, because the method would not throw IllegalArgumentException any more.

java.lang.AssertionError: Expected exception: java.lang.IllegalArgumentException
    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

That’s all on how to test expected exception in JUnit4. It is an very easy to test Java method with Junit’s annotation based approach. Now we can easily verify any Java method for both correct and incorrect set of inputs, along with exceptions for normal and exceptional cases.

Leave a Comment