Interview Questions

How To Use the "expected" Parameter Supported by the "@Test" Annotation?

JUnit Questions and Answers


(Continued from previous question...)

How To Use the "expected" Parameter Supported by the "@Test" Annotation?

The "expected" parameter supported by the "@Test" annotation allows you to test expected exception raised inside the test method. The "expected" parameter declares that a test method should throw the specified exception. If it doesn't throw an exception or if it throws a different exception than the one declared, the test fails. Otherwise, the test passes.

Here is how to specify the "expected" parameter inside the "@Test" annotation:

@Test(expected=exception_class) 
public void testMethod() {
   ...
}

Now we can simplify our test class presented in the previous question to use the "expected" parameter supported by the "@Test" annotation:

import org.junit.*;
import java.util.*;

// by FYICenter.com
public class ExpectedExceptionTest2 { 

  // test an expected exception
  @Test(expected=IndexOutOfBoundsException.class) 
  public void outOfBounds() {
    ArrayList emptyList = new ArrayList();
    Object o = emptyList.get(1);
  }
}



(Continued on next question...)

Other Interview Questions