setenv JUnitDIR /usr/local/junit ### CLASSPATH - environment variable for JAVA setenv CLASSPATH .:$JUnitDIR/junit.jar
//----------- code for Latitude.java ---------- // Latitude class developed using Unit Testing and JUnit // By Dan Hyde September 25, 2002 import javax.swing.*; public class Latitude{ private double deg; private double min; private double sec; private String hemi; // hemisphere "N" or "S" public Latitude(){ deg = 0.0; min = 0.0; sec = 0.0; hemi = "N"; } public Latitude(double d, double m, double s, String h){ deg = d; min = m; sec = s; hemi = h; } // more sophisticated than you need do! public boolean equals(Object anObject){ if( !(anObject instanceof Latitude) ) // needs ()s after ! return false; Latitude aLatitude = (Latitude) anObject; if(deg == aLatitude.deg && min == aLatitude.min && sec == aLatitude.sec){ if(hemi.equals(aLatitude.hemi)) return true; if(deg == 0.0 && min == 0.0 && sec == 0.0) return true; } return false; } }
//--------------- code for file LatitudeTest.java ------------ // LatitudeTest class for JUnit // By Dan Hyde September 25, 2002, Update September 22, 2004 // Assumes Latitude class has a default constructor, a four argument // constructor and an equals method. Much missing of the final class! // Enter "LatitudeTest" in field when you run "java test.ui.TestRunner" import junit.framework.*; // need to import test framework public class LatitudeTest extends TestCase{ private Latitude N0; private Latitude N90; public LatitudeTest(String name) { // need a constructor with String arg super(name); } protected void setUp(){ N0 = new Latitude(); N90 = new Latitude(90.0, 0.0, 0.0, "N"); } public void testLatitudeConst(){ // O degrees N from default constructor should equal // 0 degrees N from 4 arg constructor Latitude N0expected = new Latitude(0.0, 0.0, 0.0, "N"); // To check if true use assertTrue() // DONT'T use assert() which is in old articles! assertTrue( N0.equals( N0expected ) ); // 0 degrees N should be equal to 0 degrees S. Latitude S0expected = new Latitude(0.0, 0.0, 0.0, "S"); // To check if equal use assertEquals() assertEquals( N0, S0expected ); } public static Test suite(){ TestSuite suite = new TestSuite(); suite.addTest( new LatitudeTest("testLatitudeConst") ); return suite; } }
altair{224}% javac Latitude.java altair{225}% javac LatitudeTest.java
altair{226}% java junit.textui.TestRunner LatitudeTestor in graphical mode
altair{227}%java junit.swingui.TestRunner LatitudeTestIn graphical mode, you should see a green bar indicating the test was successful. The class name LatitudeTest is optional in the graphical mode. It is required in the text mode.
Note that you need two files - one with the class you are developing and the second class for the unit tests.