Simple Test Example

Suppose you are writing a Calculator class that can perform simple operations on pairs of integers. Before you even write the class, take a moment to write a few tests for it, as shown below. (By writing tests early, you start thinking about which cases might cause problems.) Then write the Calculator class, compile both classes, and run the tests to see if they pass. If they do, write a few more test methods to check other cases that you have realized are important. In this way, you can build up programs with a great deal of confidence.

import junit.framework.TestCase;
public class CalculatorTest extends TestCase {

  public void testAddition() {
    Calculator calc = new Calculator();
    // 3 + 4 = 7
    int expected = 7;
    int actual = calc.add(3, 4);
    assertEquals("adding 3 and 4", expected, actual);
  }

  public void testDivision() {
    Calculator calc = new Calculator();
    // Divide by zero shouldn't work
    try {
      calc.divide(2, 0);
      fail("Should have thrown an exception!");
    }
    catch (ArithmeticException e) {
      // Good, that's what we expect
    }
  }

}