2 Minutes To Code (β Version)

JUnit 3.10 - 2 minute tutorial

How to test whether expected Exception is thrown

If your application code is designed to throw exception when certain conditions are met, then you can verify that this is indeed so by testing for exceptions.

For this enclose the method that is expected to throw exception in a try-catch block and place the method fail() of class junit.framework.TestCase such that in a successful test scenario, the fail method all will never be reached. Consequently, if the fail method does get called, it indicates that the test has failed.

This appraoach in junit 3 is not elegant. Have a look at the exception testing flow in junit 4 which is much more intuitive.
package com.techfundaes.junit3_8_1;

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

public class TestException extends TestCase
{
	public void testTransactObject()
	{
		Account accountOne = new Account();
		accountOne.transact(50);
		
		Account accountTwo = null;
		
		try
		{
			accountOne.merge(accountTwo);
			fail("A NullPointerException should have been thrown !");
		}
		catch(NullPointerException npe)
		{
			npe.printStackTrace();
		}
		assertEquals(200, accountOne.balanceAmount);
	}
	
	public static void main(String[] args)
	{
		TestRunner.run(TestException.class);
	}

}