Junit can trace the Exception.
We can test whether the code throws desired exception or not.
The expected parameter is used along with @Test annotation.
The following code shows how to use @Test annotation to mark a method expected exception.
import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestJunit { /*from w ww .j av a 2s. c o m*/ @Test(expected = ArithmeticException.class) public void testPrintMessage() { int a = 0; int b = 1 / a; assertEquals(0,b); } }
Here is the code to run the test case.
import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; /*from w w w. j av a 2 s .com*/ public class Main { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } }
The code above generates the following result.