Unit testing method exceptions

Sometime we have to test whether a method throws proper and required exceptions or not. One way of testing is placing the method call (to be tested) inside a try catch block, as shown below

try {
    fail("Should have thrown exception");
} catch(IllegalArgumentException excep) {
} catch(Exception excep) {
    fail("Should have thrown IllegalArgumentException exception");

In the above code, we are testing three cases. In all the three cases we want the method to throw IllegalArgumentException

1) Method throws the required exception
2) Method throws some other exception
3) Method doesn’t throw any exception at all

In case 1, since the above code throws required exception, it executes the empty catch block and passes the test cases.
In case 2, since the above code throws some other exception, the test case fails by printing “Should have thrown IllegalArgumentException exception”.
In case 3, since the above code doesn’t throw any exception, the test case fails by printing “Should have thrown exception”.

Junit provides a feature to achieve all the three with no try-catch block. The below code gives an example


package Package3;

public class Class2 {
    public void method1(Boolean value) {
        if(value == null) {

        } else if(value.booleanValue()) {
            throw new IllegalArgumentException();
        } else {
            throw new NullPointerException();


package Package3;

import org.junit.Before;
import org.junit.Test;

public class Class2Test {
    private Class2 class2;

    public void setUp() {
        this.class2 = new Class2();

        public void testMethod11() {

        public void testMethod12() {

        public void testMethod13() {

We annotate the methods with @Test, to tell junit, the methods that should be executed as test cases. We also tell Junit what exceptions to be expected when they are running the test cases using expected attribute of @Test annotation. If the expected exception is not thrown test case fails.

In the example,
Case 1 is tested by testMethod11
Case 2 is tested by testMethod12
Case 3 is tested by testMethod13


Leave a Reply