2 Minutes To Code (β Version)

JUnit 4.10 - 2 minute tutorial

How to set environment before every test method and cleanup after the test method

If you need to do an initialization every time a test method is run, then junit provides an annotation org.junit.Before for this. You can annotate one method with Before and junit will run that method before running a test method.

Similarly, if you need to do a clean-up or free some resources after a test method is run, then use the org.junit.After annotation. You can annotate one method with After and junit will run that method after running a test method.

In the same way, if you need to do some initialization and corresponding clean-up once for the test class, the previous page explains how to do it.
package com.techfundaes.junit4Bag;

import java.util.ArrayList;

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

public class TestMethodSetUp
	public static Account account = null;
	public void createMethodEnvironMent()
		account = new Account();
		System.out.println("Set Up Method Environment");
	public void clearMethodEnvironMent()
		account = null;
		System.out.println("Cleared Method Environment");
	public void transactBooleanTest()
		assertTrue("Test Failed Message", account.transact(5).balanceAmount == 5);
	public void transactObjectTest()
		Account accountOne = new Account();
		assertEquals("Test Failed Message", account, accountOne);