2 Minutes To Code (β Version)

JUnit 3.10 - 2 minute tutorial

How to set up class environment before the methods in a class are tested

If you need to set up the test environment before any test method is executed and clean-up or release the resources once tests have been run, then junit provides a way to do this.

Put methods protected void setUp() and protected void tearDown() in the test class and junit 3 will run these once per class, at the beginning of testing the class and at the end respectively.

Unlike junit 4, which provides a way to run one method each before and after every single test method through annotations org.junit.Before and org.junit.After, junit 3 does not have any such mechanism.
package com.techfundaes.junit3_8_1;

import junit.framework.TestCase;
import junit.textui.TestRunner;

public class TestSetUpEnvironment extends TestCase
{
	static Account account = null;
	
	protected void setUp()
	{
		account = new Account();
		account.balanceAmount = 100;
		System.out.println("Set up environment !");
	}
	
	protected void tearDown()
	{
		account = null;
		System.out.println("Tore Down environment !");
	}
	
	public void testTransact()
	{
		account.transact(50);
		assertTrue(account.balanceAmount == 150);
	}
	public void testTransactObject()
	{
		Account accountTwo = new Account();
		accountTwo.transact(150);
		
		account.merge(accountTwo);
		assertEquals(250, account.balanceAmount);
	}
	
	public static void main(String[] args)
	{
		TestRunner.run(TestSetUpEnvironment.class);
	}
}