Saturday, April 1, 2017

JUnit 4 Tutorial - Test Exception thrown by Java Method with Example

One part of unit testing a Java method is checking exception thrown by that method. A Java unit test should verify the correct exception thrown in the exceptional case and no exception should be thrown in normal case. In JUnit 3.XX, there was no direct support to pass or fail a test based upon exception thrown by a Java method. JUnit4 address this issue and provides an easy, and readable way to test exception thrown by a Java method. There are many situations when you need to test the exception thrown by any method in Java. A classical example of this is testing API methods which should throw IllegalArgumentException if arguments passed to the method are not matching to pre-conditions.


In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException.class) annotation. You can replace IllegalArgumentException.class with any other exception e.g. NullPointerException.class or ArithmeticException.class etc.

The bottom line is that JUnit 4 will execute that test and check if method actually throws the expected exception or not. If the method throws expected exception, specified as "expected", then JUnit 4 will pass that test, but if a method throws any other exception, or doesn't throw any exception than JUnit4 will fail that particular test.

And, if you are new to unit testing and just looking for good online training courses to learn unit testing in Java then I highly recommend you check out Learn Java Unit Testing with JUnit 5 in the 20 Steps course by Ranga Rao on Udemy. It's a good course to learn JUnit 5 in easy to follow steps.






Unit test to check Exception thrown by Java method – JUnit 4 Example

JUnit tutorial example to test exception thrown by Java method
In order to test any Java method for throwing an exception in JUnit4,  You need to ensure that the argument provided to that method, from the test must result in expected Exception, Otherwise, the JUnit test will fail. Here is an example of how to test exception thrown in JUnit 4 by testing a method called speed(), which returns speed as distance/time, but before calculating speed it checks wheter time and distance is positive or not, and if time is zero or negtaive it throws IllegalArgumentException. Let’s write a JUnit test to test this method for an exception, just remember that we need to pass an argument, which result in IllegalArgumentException.

here is the exmple of source class:

public class SpeedUtils {
    
    public int speed (int distance, int time){
        if(distance < 0 || time <= 0){
            throw new IllegalArgumentException("distance: " + distance
                                                + " time: " + time);
        }      
        return distance/time;
    }
}

and here is the example of JUnit 4 test case for Exception testing, you can see that our testSpeed() method is annotated with @Test(expected=IllegalArgumentException.class), which means it expect an illegalArgumentException, when you run this JUnit test.

public class JUnitExceptionTest {
  
    /**
     * Test of speed method, of class JUnit4ExceptionTest.
     */
    @Test(expected=IllegalArgumentException.class)
    public void testSpeed() {
        System.out.println("speed");
        int distance = 0;
        int time = 0;
        JUnit4ExceptionTest instance = new JUnit4ExceptionTest();
        int expResult = 0;
        int result = instance.speed(distance, time); //shold throw exception
        assertEquals(expResult, result);     
    }
}

The test will be pass with current arguments, but if you change arguments test will be failed like below because it won’t get IllegalArgumentException any more.

Testcase: testSpeed(test.JUnit4ExceptionTest):  FAILED
Expected exception: java.lang.IllegalArgumentException
junit.framework.AssertionFailedError: Expected exception: java.lang.IllegalArgumentExcepti

That's all on how to test exceptions in JUnit4. It’s extremely easy to test the Java method with JUnit4’s annotation-based approach. Now you can easily verify any Java method for both correct and incorrect sets of inputs, along with exceptions for normal and exceptional cases. If you are writing a public API, which is intended to be used by others, you must provide unit test for checking exception thrown by a method, it’s imperative for any public API author.

Further Learning
Unit Testing In Java With JUnit
JUnit and Mockito Crash Course
Learn Unit Testing with Junit & Mockito in 30 Steps

Related JUnit Testing Tutorials from Javarevisited Blog

1 comment :

Anonymous said...

How do you verify if a test method throws exception in JUnit 3, where you don't have this @Test(expected) parameters available? Well, you can use the traditional catch block and if code throws exception then it pass otherwise fail.

Post a Comment