2 Minutes To Code (β Version)

JUnit 4.10 - 2 minute tutorial

How to set environment before running any test method in a class

If you need to do an initialization once before testing all methods, then junit provides an annotation org.junit.BeforeClass for this. You can annotate one method with BeforeClass and junit will run that method before running any test method.

Similarly, if you need to do a clean-up or free some resources after all the tests are done, then use the org.junit.AfterClass annotation. You can annotate one method with AfterClass and junit will run that method after running all tets methods.

In the same way, if you need to do some initialization and corresponding clean-up after each and every method, the next page explains how to do it.
package com.techfundaes.junit4Bag;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class TestClassSetUp
{
	public static Account account = null;
	
	@BeforeClass
	public static void createEnvironMent()
	{
		account = new Account();
		System.out.println("Set Up Environment");
	}
	
	@AfterClass
	public static void clearEnvironMent()
	{
		account = null;
		System.out.println("Cleared Environment");
	}
	
	@Test
	public void testIsLoggedIn()
	{
		assertTrue(account.transact(5).balanceAmount == 5);
	}
}