JUnit 4 Tutorial - Test Exception thrown by Java Method with Example

One part of unit testing a Java method is checking exception thrown by that method. A Java unit test should verify correct exception thrown in exceptional case and no exception should be thrown in normal case. In JUnit 3.XX, there was no direct support to pass or fail a test based upon exception thrown by a Java method. JUnit4 address this issue and provides an easy, and readable way to test exception thrown by a Java method. There are many situations when you need to  test exception thrown by any method in Java. Classical example of this is testing API methods which should throw IllegalArgumentException if arguments passed to method are not matching to pre-conditions. In order to test 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. Bottom line is that JUnit 4 will execute that test and check if method actually throws expected exception or not. If method throws expected exception, specified as "expected", than JUnit 4 will pass that test, but if method throws any other exception, or doesn't throw any exception than JUnit4 will fail that particular test.
Read more »

0 Response to "JUnit 4 Tutorial - Test Exception thrown by Java Method with Example"

Posting Komentar