SE450: JUnit: An example [38/41] ![]() ![]() ![]() |
Here is an example set of tests that exercise the
getGrade
methods of the three strategies from
the last homework assignment. These tests do not offer a
guarantee that the implementation is correct for every case,
but you can see that it covers the differences in the
different classes.
package se450.mwright1.hw2; import junit.framework.*; /** * A sample test case, testing <code>se450.mwright1.hw2.Student</code>. * */ public class StudentTest extends TestCase { protected Student student; protected void setUp() { student = new Student("Test", "Student"); student.setProject1(50); student.setProject2(75); student.setProject3(100); student.setMidterm(66); student.setFinalExam(90); } public StudentTest(String name) { super(name); } public static Test suite() { return new TestSuite(StudentTest.class); } public void testConstructor() { assertTrue(student.getFirst().equals("Test")); assertTrue(student.getLast().equals("Student")); } public void testGrade() { assertTrue(student.getTotal() == 78); assertTrue(student.getGrade().equals("C")); } public void testToString() { assertTrue(student.toString().equals("[Student: Test Student ]")); } }
When writing Unit tests, ask yourself these questions:
Write these types of tests. Then, whenever you find a bug, add a test for that bug. Write the test that exposes your bug first. Then, modify your code to make it pass. Then, never get rid of the test and the bug will never reappear.