Testing exceptions in JUnit Tests

Pooja Londhe
Globant
Published in
1 min readJan 9, 2020

JUnit provides the facility to trace the exception and also to check whether the code is throwing an expected exception or not.

Junit4 provides a way for exception testing, you can use

  • Optional parameter (expected) of @test annotation

While performing exception testing for the code, you need to ensure that the exception class you are providing in that optional parameter of @test annotation is the same, otherwise our JUnit test would fail because it will not match to the exception you are expecting from the method.

Example : @Test(expected=NullPointerException.class)

By using “expected” parameter, you can specify the exception name our test may throw. In the above example, you are using “NullPointerException” which will be thrown by the test if a developer uses an argument that is not permitted.

Example to test sorting array with null value as input:

public class SortArrayTest {
@Test
public void sortNullArray(){
int [] numbers = null;
Arrays.sort(numbers);
}
}

If will run the above test case it will fail with the exception as “java.lang.NullPointerException”.

So if we want to write a test case for testing “NullPointerException” we can make changes to the above code like:

public class SortArrayTest {
@Test(expected = NullPointerException.class)
public void sortNullArray(){
int [] numbers = null;
Arrays.sort(numbers);
}
}

So now our test case will give us success and we can able to trace the exception.

Happy Coding :)

--

--