import junit.framework.TestCase; import java.util.Calendar; import java.text.DateFormat; // Eclipse/WebSphere has the required jar file and it is // available from http://junit.org // Run the tests from Command Prompt: // java -classpath .;junit.jar CalcTimeTest.java // or “Run As JUnit Test” in Eclipse/WebSphere public class CalcTimeTest extends TestCase { /* * test Calendar.setTimeInMillis() */ public void testOneDayByMillis() { long now = System.currentTimeMillis(); Calendar today = Calendar.getInstance(); today.setTimeInMillis( now ); Calendar tomorrow = Calendar.getInstance(); tomorrow.setTimeInMillis( now + 1000 * 60 * 60 * 24 ); Calendar difference = Calendar.getInstance(); difference.setTimeInMillis( tomorrow.getTimeInMillis() - today.getTimeInMillis() ); assertEquals( difference.getTimeInMillis(), 1000 * 60 * 60 * 24 ); } /* * test Calendar.roll() */ public void testRollOneDay() { long now = System.currentTimeMillis(); Calendar today = Calendar.getInstance(); today.setTimeInMillis( now ); Calendar tomorrow = Calendar.getInstance(); tomorrow.setTimeInMillis( now ); tomorrow.roll( Calendar.DATE, true ); Calendar difference = Calendar.getInstance(); difference.setTimeInMillis( tomorrow.getTimeInMillis() - today.getTimeInMillis() ); assertEquals( difference.getTimeInMillis(), 1000 * 60 * 60 * 24 ); } /* * test Calendar.add() */ public void testAddDay() { long now = System.currentTimeMillis(); Calendar today = Calendar.getInstance(); today.setTimeInMillis( now ); Calendar tomorrow = Calendar.getInstance(); tomorrow.setTimeInMillis( now ); tomorrow.add( Calendar.DATE, 1 ); Calendar difference = Calendar.getInstance(); difference.setTimeInMillis( tomorrow.getTimeInMillis() - today.getTimeInMillis() ); assertEquals( difference.getTimeInMillis(), 1000 * 60 * 60 * 24 ); } /* * test Calendar is lenient with invalid dates */ public void testSetYYYYMMDD() { Calendar today = Calendar.getInstance(); today.set( 2008, 01, 32 ); Calendar tomorrow = Calendar.getInstance(); tomorrow.set( 2008, 01, 33 ); Calendar difference = Calendar.getInstance(); difference.setTimeInMillis( tomorrow.getTimeInMillis() - today.getTimeInMillis() ); assertEquals( difference.getTimeInMillis(), 1000 * 60 * 60 * 24 ); } /* * test Calendar is lenient with invalid dates */ public void testYYYYMMDDFormat() { Calendar today = Calendar.getInstance(); today.set( 2008, 01, 32 ); // Remember: month Zero is January DateFormat prettyPrint = DateFormat.getDateInstance(); assertEquals( prettyPrint.format( today.getTime() ), "Mar 3, 2008"); } public static void main(String[] args) { junit.swingui.TestRunner.run(CalcTimeTest.class); // OLD SCHOOL! } }