Rectangle 27 3

Java annotation @Test Parameters

The JUnit @Test annotation is used to indicate that a method should be called to run a test. @Test can contain two types of parameter:

Exceptions

When the test is expected to throw an exception, we can indicate this by adding expected = <exception>.class after @Test, where <exception> is the name of the expected exception.

//fail if IOException is not thrown
@Test(expected = IOException.class)

Time-out

When a test needs to complete within a specific time period, we can add a parameter to @Test to fail if the test takes too long. The value in the parameter is measured in milliseconds.

//timeout after 500ms
@Test(timeout = 500)
Note Java annotations
Rectangle 27 1

Restricting an annotation's application by using @Target

The type of element that an annotation can be applied to can be restricted using the @Target meta-annotation.

The @Target declaration takes the form of @Target(ElementType.<ELEMENT_TYPE>), where <ELEMENT_TYPE> is an element type from a predefined list. The available elements are:

  1. ANNOTATION_TYPE
  2. CONSTRUCTOR
  3. FIELD
  4. LOCAL_VARIABLE
  5. METHOD
  6. PARAMETER
  7. TYPE (any type of element)

For example:

@Target(ElementType.CONSTRUCTOR)

The annotation that is annotated with this will only be able to be applied to constructors.

Note Java annotations restrictions