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;
    public static void suiteSetup(){
        assertEquals(0, counter);
    public JUnitLifeCycle(){
    public void prepareTest(){
    public void performFirstTest(){
        assertEquals(3, counter);
    public void performSecondTest(){
        assertEquals(7, counter);
    public void cleanupTest(){
    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 *