JUnit 4 Showcase – Setting up and optimising unit tests

JUnit 4 has been a major rewrite of the JUnit API mainly:

  • it uses annotations
  • a test can be any POJO class, no need to extend TestCase or have special name conventions for test classes and methods. Although the main rules remain that each JUnit method needs to be public void and have no arguments.

In case we want to run initialisation code prior and post each test case (JUnit method) we can use the @Before and @After annotations saving us from the trouble of initialising the same code in each test case.

Similarly, if we need to run initialisation code prior and post every test class this time we can use the @BeforeClass and @AfterClass annotation. Other than these annotations, these particular methods need to be static.

Having as an example the following code:

package com.dimitrisli.junitshowcase.beforeAfter;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class BeforeAfterTest {

	public static void initialiseClass(){
		System.out.println("init class");
	public void initialiseTest(){
		System.out.println("init test");
	public void test1(){
		System.out.println("inside test1");

	public void test2(){
		System.out.println("inside test2");
	public void teardownTest(){
		System.out.println("teardown test");
	public static void teardownClass(){
		System.out.println("teardown class");

produces the output:

init class
init test
inside test1
teardown test
init test
inside test2
teardown test
teardown class

The code can be found in this Github repository.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s