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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*