Handling exceptions in JUnit

In this blogpost, we will have a look at several ways to handle run exceptions in JUnit.

Using @Test annotation attribute:

This is one of the simplest ways to handle a run time exception in JUnit test case. This can be achieved by setting expected attribute value with the type of exception, that might occur.

@Test(expected=ArithmeticException.class)

Create a class containing a @test method as below.

import org.junit.Test;
import org.junit.rules.ExpectedException;

public class ExceptionTest {

@Test(expected= ArithmeticException.class)
public void exceptionTest() {
System.out.println(“Inside exception test…”);
int i = 1/0;
System.out.println(“After exception…”);
}

}

Run the test class as JUnit Test. The divide by zero exception will be handled by expected attribute.

Using @Rule annotation:

This is another way of handling exceptions in JUnit, refer to the below code snippet.

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class ExceptionTest {

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void test() {
thrown.expect(ArithmeticException.class);
thrown.expectMessage(“exc caught”);
System.out.println(“Inside exception test”);
int i = 1 / 0;
System.out.println(i);
System.out.println(“After exc”);
}

Run the test case class as JUnit test case, and you will see the output as below.

junit-exception-test-runwith.PNG

Hope it works for you!!

Cheers 🙂

Advertisements

#runwith, #exception-test-in-junit, #expected, #handling-exception-in-junit