JUnit 4 Annotation Example

This tutorial explains the basic usage of JUnit 4 annotations. JUnit is the most popular Unit testing framework most widely used by the Java developers. After the release of Java 5.0 annotations, JUnit 4 has updated to support the annotation programming for the testing methods. Also it introduced @BeforeClass and @AfterClass methods which has to be declared as static methods. Look at the below example with annotations.

package javabeat.net.junit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;

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

public class JUnitTestExample {

	private ArrayList<String> list;

	@BeforeClass
	public static void oneTimeSetUp() {
		//Initialization code goes here
		System.out.println("@BeforeClass");
	}

	@AfterClass
	public static void oneTimeTearDown() {
		//Release your resources here
		System.out.println("@AfterClass");
	}

	@Before
	public void setUp() {
		list = new ArrayList<String>();
		System.out.println("@Before - setup()");
	}

	@After
	public void tearDown() {
		list.clear();
		System.out.println("@After - teardown()");
	}

	@Test
	public void testEmptyCollection() {
		assertTrue(list.isEmpty());
		System.out.println("@Test Method 1");
	}

	@Test
	public void testOneItemCollection() {
		list.add("String1");
		assertEquals("String1", list.get(0));
		System.out.println("@Test Method 2");
	}
}

If you run the above example, the output will be:

@BeforeClass
@Before - setup()
@Test Method 2
@After - teardown()
@Before - setup()
@Test Method 1
@After - teardown()
@AfterClass

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>