Test algorithm : TestCase « JUnit « Java Tutorial






import junit.framework.TestCase;

public class TestLargest extends TestCase {

  public TestLargest(String name) {
    super(name);
  }

  public void testOrder() {
    assertEquals(9, Largest.largest(new int[] { 9, 8, 7 }));
    assertEquals(9, Largest.largest(new int[] { 8, 9, 7 }));
    assertEquals(9, Largest.largest(new int[] { 7, 8, 9 }));
  }

  public void testEmpty() {
    try {
      Largest.largest(new int[] {});
      fail("Should have thrown an exception");
    } catch (RuntimeException e) {
      assertTrue(true);
    }
  }

  public void testOrder2() {
    int[] arr = new int[3];
    arr[0] = 8;
    arr[1] = 9;
    arr[2] = 7;
    assertEquals(9, Largest.largest(arr));
  }
}

class Largest {
  public static int largest(int[] list) {
    int index, max = Integer.MAX_VALUE;
    if (list.length == 0) {
      throw new RuntimeException("Empty list");
    }
    for (index = 0; index < list.length - 1; index++) {
      if (list[index] > max) {
        max = list[index];
      }
    }
    return max;
  }
}








39.2.TestCase
39.2.1.extends TestCase
39.2.2.Use assertEquals in a test method
39.2.3.JUnit Test Composition
39.2.4.Per-Test Setup and Tear-Down
39.2.5.Test Skeleton
39.2.6.Test your stack structure
39.2.7.Test algorithm
39.2.8.Init class being tested in test case method