// APS101, Winter 2009: Lecture 13 (Feb. 5) // // Review: last time we kept looking at static variables/methods, and constants. // We also covered a number of String methods: // ex. charAt, substring, indexOf, length. // At the end, we wrote OurString.getFirstVowel(String). // But what was the problem with it? // Any ideas about how to fix it? Maybe using ASCII values? // Today we'll talk about testing your programs using JUnit. // Take a look at CarTester.java. // Also, take a look at BankAccountTester.java, which we started writing in class. FORMAL DEFINITION: -----> Testing code using JUnit Here are the general instructions about how to create a test class for a class called MyClass: 1. we extend the TestCase class and call it MyClassTester e.g. import junit.framework.TestCase; public class MyClassTester extends TestCase { .... } 2. for every public method of our class (including constructors) we write a 'tester method' * a tester method for method "m1", e.g., has the following syntax: public void testM1(){ //body } where in the body you usually create some objects and call the m1 method. Then you check whether the expected values are returned. We do this by using "assertTrue"/"assertFalse" or in general "assertEquals(...)" exercise: complete the testWithdraw method in BankAccountTester WHAT WE DID IN LECTURE: import junit.framework.TestCase; // assertEquals(expectedValue, actualValue) // if these two values are equal, then the test passes. // if they're not, then the test fails. TestCase.assertEquals(5, 5) TestCase.assertEquals(5, 6) TestCase.assertEquals("This test will fail!", 5, 6) String s = "hi"; TestCase.assertEquals("hi", s) TestCase.assertEquals(s, "hi") TestCase.assertEquals("hello", s) int i = 5; TestCase.assertEquals(5, i) TestCase.assertEquals(6, i) Integer i1 = new Integer(5); Integer i2 = new Integer(5); TestCase.assertEquals(i1, i2) Car c1 = new Car(2005, "Honda", "Civic", "red", 10.0) Car c2 = new Car(2005, "Honda", "Civic", "red", 10.0) TestCase.assertEquals(c1, c2) c1 == c2 TestCase.assertNull(null) TestCase.assertNull("hi") TestCase.assertEquals(!(null), "hi") // this doesn't work! TestCase.assertEquals(null, "hi") TestCase.assertNotNull("hi") TestCase.assertTrue(true) TestCase.assertTrue(false) TestCase.assertFalse(false) TestCase.assertFalse(true) TestCase.assertTrue(5 == 5) TestCase.assertTrue(5 == 6) TestCase.assertTrue("hi") // this also doesn't work! TestCase.assertNotNull(c1.getYear()); // when comparing doubles, you can specify a margin of error (delta): // assertEquals(expectedValue, actualValue, delta) TestCase.assertEquals(5.6, 5.6) TestCase.assertEquals(5.6, 5.5) TestCase.assertEquals(5.6, 5.5, 0.1) TestCase.assertEquals(5.6, 5.5, 0.01) // this also allows you to compare double with an int! TestCase.assertEquals(6.0, 6, 0.1) TestCase.assertEquals(6.0, 6) // error! TestCase.assertEquals(6.0, 6, 0.0)