The JUnit Test Life Cycle

Running a test suite in JUnit follows a defined set of steps. These steps can help you modularize the tests and reuse as much code as possible.

The annotations were introduced in JUnit 4 (before JUnit 4 you would need your class to extend TestSuite) .

If you have some computations, such as preparing the filesystem for the upcoming test, or some pretesting notification to a build server, then the place to do such operations is a method annotated with @BeforeClass. It is a void returning public static method.
Similarly there is the annotation @AfterClass. Methods with such annotation are invoked after all the tests have completed.

In between the above mentioned annotations, methods with the annotations @Before, @Test and @After are run. @Before methods contain your test setup. The test is then run in @Test methods. And following a successful, or unsuccessful, run of the test, the @After annotated methods are called (This will clean up anything the test may have dirtied, such as a database or filesystem, or even perform some post-test logging) .

Here is an example:

public class JUnitLifeCycle {
 
    private static int counter = 0;
 
    @BeforeClass
    public static void suiteSetup(){
        assertEquals(0, counter);
        counter++;
    }
 
    public JUnitLifeCycle(){
        assertTrue(Arrays.asList(1,5).contains(counter));
        counter++;
    }
 
    @Before
    public void prepareTest(){
        assertTrue(Arrays.asList(2,6).contains(counter));
        counter++;
    }
 
    @Test
    public void performFirstTest(){
        assertEquals(3, counter);
        counter++;
    }
 
    @Test
    public void performSecondTest(){
        assertEquals(7, counter);
        counter++;
    }
 
    @After
    public void cleanupTest(){
        assertTrue(Arrays.asList(4,8).contains(counter));
        counter++;
    }
 
    @AfterClass
    public static void suiteFinished(){
        assertEquals(9, counter);
    }
}

The sequence of the run is captured in:

counter in suiteSetup is: 0
counter in constructor is: 1
counter in prepareTest is: 2
counter in performFirstTest is: 3
counter in cleanupTest is: 4
counter in constructor is: 5
counter in prepareTest is: 6
counter in performSecondTest is: 7
counter in cleanupTest is: 8
counter in suiteFinished is: 9

The test runner instantiates JUnitLifeCycle twice, one for each @Test.

Leave Comment

Your email address will not be published. Required fields are marked *