Home

 

What is new in JUnit 4.x

For the first time in its history, JUnit 4 has significant changes to previous releases. It simplifies testing by using the annotation feature, which was introduced in Java 5 (JDK 1.5). One helpful feature is that tests no longer rely on sub classing, reflection, and naming conventions. JUnit 4 allows you to mark any method in any class as an executable test case, just by adding the @Test annotation in front of the method. Table | 3-1 lists some important annotations.

Table 23-1

Annotation name Description
@Test Marks that this method is a test method.
@Test(expected= ExceptionClassName.class) Tests if the method throws the named exception.
@Test(timeout=100) Fails if execution of method takes longer than 100 milliseconds.
@Ignore Ignores the test method.
@BeforeClass Marks the method that must be executed once before the start of all the tests; for example, to connect to the database.
@AfterClass Marks the method that must be executed once after the execution of all the tests; for example, to disconnect from the database.
@Before Marks the method that must be executed before each test (setUp).
@After Marks the method that must be executed after each test (tearDown).

JUnit 4.x annotation overview

There is an Open Source project available called JUnit 4 Extensions. It provides the @prerequisite(requires="methodName") annotation, which can be very helpful. It allows you to call another method before entering the test. The test will only be executed if this method returns true. An example is provided next.

You can find more information about the JUnit 4 Extension project at:

http://www.junitext.org/
ibm.com/redbooks