If you want to test a method that will throw an exception under a specific condition,
you can:
Put the test code inside a "try" block".
Catch the expected exception object.
Assert the exception object with Assert.assertNotNull().
JUnit runner will fail this test if the test code did not raise the expected exception.
Here is a good test class that test the expected IndexOutOfBoundsException
exception raised by the get() method of the ArrayList class:
import org.junit.*;
import java.util.*;
// by FYICenter.com
public class ExpectedExceptionTest1 {
@Test public void outOfBounds() {
ArrayList emptyList = new ArrayList
But there a better way to test the expected exception provided by the JUnit @Test annotation.
See the next question.