Unit Testing Java Code

Objectives

Prerequisites

Definitions

Unit
A part of a program, ranging from as small as a single method to as large as all the classes in a package, often a single class
Unit test
Code to test a unit of a program
JUnit
An open source library of Java code that aids unit testing of Java programs; available from junit.org. JUnit's purpose is to automate the verfication of unit test results.

Example


import org.junit.Test;
import static org.junit.Assert.*;
import account.*;


public class TestAccount {
	private static final double ANNUAL_RATE = 0.035;
	private static final double OVERDRAFT_LIMIT = 500;
	private static final double DELTA = 0.001;


	@Test  // This annotation must appear before each unit test method
	public void testSavingsAccount() {
		SavingsAccount a = new SavingsAccount(ANNUAL_RATE);

		Date now = new Date();
		Date opened = a.getDateOpened();

		/* The assert methods are part of the org.junit.Assert class.
		 * assertEquals follows this format:
		 * assertEquals(expected_value, actual_value, acceptable_difference);
		 */
		assertEquals(now.getTime(), opened.getTime(), 1000);

		assertEquals(1, a.getId());
		assertEquals(ANNUAL_RATE, a.getAnnualRate(), 0);

		// Ensure the balance is 0
		assertEquals(0, a.getBalance(), 0);

		// Deposit $50 and ensure the balance is $50.
		a.deposit(50);
		assertEquals(50, a.getBalance(), DELTA);

		// Withdraw $40 and ensure the balance is $10.
		a.withdraw(40);
		assertEquals(10, a.getBalance(), DELTA);

		// Attempt to withdraw more money than is in the
		// account and ensure the balance didn't change.
		a.withdraw(40);
		assertEquals(10, a.getBalance(), DELTA);

		// Withdraw $10 and ensure the balance is 0.
		a.withdraw(10);
		assertEquals(0, a.getBalance(), DELTA);

		/* There are several other assert methods in the org.junit.Assert
		 * class, notably assertFalse, assertTrue, assertNull, assertSame,
		 * and assertArrayEquals.  See the online java docs for junit. */

		assertTrue(a instanceof Account);
	}


	@Test
	public void testBank() {
		Bank bank = new Bank();

		// Add two accounts to the bank.
		Account sa = new SavingsAccount(ANNUAL_RATE);
		Account ca = new CheckingAccount(ANNUAL_RATE, OVERDRAFT_LIMIT);
		bank.addAccount(sa);
		bank.addAccount(ca);

		// Find the first the account that was just added.
		Account f = bank.findAccount(sa.getId());
		assertSame(f, sa);

		// Attempt to find an account that doesn't exist.
		Account f = bank.findAccount(ca.getId() + 1);
		assertNull(f);
	}
}

Copyright © 2010, Maia L.L.C.  All rights reserved.