Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Tuesday, July 27, 2021

How to test Exception thrown by a Java Method in JUnit? Example

One part of unit testing a Java method is checking exceptions 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 a normal case. In JUnit 3.XX, there was no direct support to pass or fail a test based upon the exception thrown by a Java method. JUnit4 address this issue and provides an easy, and readable way to test exceptions 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 the method actually throws the expected exception or not. If the method throws the 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.

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.
    public void testSpeed() {
        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 a unit test for checking exceptions thrown by a method, it’s imperative for any public API author.

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