Testing Classes

Context

A class should be unit tested before integrating it with a larger program. Bugs are easier to find and fix without dealing with complex interactions between classes. By including a main method in each class to test just that class, the testing can be accomplished in an easy and uniform manner.

Example


public class Date
{  private int year;
   private int month;
   private int day;

   public Date(int aYear, int aMonth, int aDay)
   {  this.year = aYear;
      this.month = aMonth;
      this.day = aDay;
   }

   /** Is this date before date d? */
   public boolean before(Date d)
   {  return (this.year < d.year) || 
             (this.year == d.year && this.month < d.month) ||
             (this.year == d.year && this.month == d.month && this.day < d.day);
   }

   /** Convert a Date object to a String */
   public String toString()
   {  return this.year + "/" + this.month + "/" + this.day;
   }


   /** Test the class. */
   public static void main(String[] args)
   {  Date d1 = new Date(2005, 12, 25);
      Date d2 = new Date(2005, 12, 24);

      String t1 = d1 + " before " + d2;
      String t2 = d2 + " before " + d1;
      String t3 = d1 + " before " + d1;

      test("t1", d1.before(d2), false);
      test("t2", d2.before(d1), true);
      test("t3", d1.before(d1), false);
   }

   private static void test(String msg, boolean answer, boolean expected)
   {  if (answer == expected)
      {  System.out.print("passed ");
      } else
      {  System.out.println("FAILED ");
      }
      System.out.println("Test: '" + msg + "'");
      System.out.println("       Expected: '" + expected + "'");
      System.out.println("       Got:      '" + expected + "'");
      System.out.println();
   }
}

Pattern

public class <name-of-class>
{  <instance-variables>
   <methods>

   /** Test the class. */
   public static void main(String[] args)
   {
      <code-to-test-class>
      System.out.println(<message-to-report-test-results>);
   }
}

Notes

Related Patterns