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;

	public static void oneTimeSetUp() {
		//Initialization code goes here

	public static void oneTimeTearDown() {
		//Release your resources here

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

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

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

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

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

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

Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!