Table of contents
1.
Introduction
2.
Exceptions Handling
3.
@Test(expected) Method
3.1.
Program
3.2.
Test
3.3.
Output
4.
Testing Exceptions using @Rule
4.1.
Example Test
4.2.
Output
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

JUnit Exceptions Test

Author Aditya Anand
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Welcome readers! In this blog, we will learn about exception handling in JUnit. Sometimes we want our function to throw a particular exception. JUnit provides a way to assert exceptions. We can use the @Test(expected) Method or @Rule annotation to assert exceptions.

Let's get started, and I hope you learn a lot from this tutorial.

Exceptions Handling

JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not.

JUnit provides an easy and readable way for exception testing. You can use the Optional parameter (expected) of @test annotation, and to trace the information,” fail()” can be used.

While Testing exceptions, you need to ensure that the exception class you provide in that optional parameter of @test annotation is the same. This is because you expect an exception from the Unit Testing method; otherwise, the unit test would fail.

@Test(expected) Method

The expected parameter is used along with @Test annotation.

Using the “expected” parameter can specify the exception name our test may throw.

Program

Let’s start our example by creating a sample class called divideByZero.java, and it contains a simple method that will print in the console that this method is trying to divide by zero, which will throw Arithmetic Exception

package com.aditya04848.junit.helper;

public class divideByZero{

    public void function(){

        System.out.println("Trying to divide by zero will throw Arithmetic Exception");
        int divide = 1/0;
    }
}
You can also try this code with Online Java Compiler
Run Code

Test

We have to create a test file for the above class called divideByZeroTest.java. We are simply creating an obj of the divideByZero class and calling it inside the @Test.

Since inside the @Test annotation, we have provided the expected argument value to be ArithmeticException.class, which means this test is expecting an ArithmeticException.

Now when obj.function() is called, it tries to divide by zero and throws an ArithmeticException, which is why the test is successfully passed.

package com.aditya04848.junit.helper;
import org.junit.Test;

public class divideByZeroTest {
   
    divideByZero obj = new divideByZero();

    @Test(expected = ArithmeticException.class)
    public void functionTest(){
        obj.function();      
    }
}
You can also try this code with Online Java Compiler
Run Code

Output

Following will be the output in console and JUnit.

Output Console:

Output JUnit:

Testing Exceptions using @Rule

@Test method is useful only when we want to assert that a specific exception is thrown or not.

We can use the ExpectedException rule to verify some other properties of the exception.

In the below example code, apart from asserting the expected exception, we're also asserting that the code that attempts to parse an Integer value will result in a NumberFormatException with the message "For input string."

Example Test

In this example test, we create an exception rule under @Rule annotationand using exceptionRule.expect(), we are excepting the NumberFormatException exception. Since Integer.parseInt("abc") will throw NumberFormatException, the following test code will pass successfully. We can also check the expectMessage using exceptionRule.

package com.aditya04848.junit.helper;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class NumberFormatExpection { 
    @Rule
    public ExpectedException exceptionRule = ExpectedException.none();
    @Test
    public void testFunction() {
        exceptionRule.expect(NumberFormatException.class);
        exceptionRule.expectMessage("For input string");
        Integer.parseInt("abc");
    }
}
You can also try this code with Online Java Compiler
Run Code

Output

FAQs

  1. What happens if a method throws an exception In JUnit?
    JUnit will fail the test if the method does throw the exception. Note the difference: that test case does not test that the exception is thrown and caught (an implementation detail), it tests that the method does not throw or propagate an exception in the situation that a call to csvReader.read will throw an exception.
     
  2. When to use try/catch In JUnit?
    The try/catch has its limits. This approach is helpful for simple cases, like a testing message in the exception or domain object.
     
  3. Does the @before method get its instance in JUnit?
    Each test creates an instance of the test class and invokes the test. After all, tests are executed, the "@AfterAll" annotated static methods are called.
     
  4. How do I uninstall JUnit?
    Delete the directory structure where you unzipped the JUnit distribution.
    Remove junit.jar from the CLASSPATH.
    JUnit does not modify the registry, so removing all the files will thoroughly uninstall it.

Key Takeaways

In conclusion, exception handling is significant because we expect a method to throw an exception in some situations. For example, if we have a divide method and 0 is given as a denominator argument, we expect this divide method to throw Arithmetic Exception.

In JUnit, we can assert exceptions using the @Test(exception) method, and we just have to provide the value of exception to be equal to the expected exception this test should throw. We can also assert exceptions using @Rule annotation.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Live masterclass