Junit’s annotation based expected exception testing

Junit provides an option of tracing exception thrown by a Java method. There are different ways of handling exceptions in JUnit tests. Standard Junit’s org.junit.Test annotation offers expected attribute that allows us specifying the a Throwable to cause a test method to succeed if an exception of the specified class is thrown by the method. A Java unit test should verify correct exception thrown in exceptional case and no exception should be thrown in normal case. For this to test exception thrown by a Java method using @Test(expected=””) we need to use at least Junit 4.7. One of the many situations where we need to test exception thrown by a Java method is testing an API method that should throw IllegalArgumentException if arguments passed to the method are not matching to pre-conditions. For example, in order to test that we need to use @Test(expected=IllegalArgumentException.class) annotation. We can replace IllegalArgumentException.class with any other exception e.g. NullPointerException.class or ArithmeticException.class etc as per the requirment. In order to test any Java method for throwing excpetion, we need to ensure that arguments provided to the method, from the test must result in expected Exception, otherwise JUnit test will fail. Continue reading “Junit’s annotation based expected exception testing”