//执行测试的类(JUnit版)import junit.framework.*;public class testCar extends TestCase {protected int expectedWheels;protected Car myCar;public testCar(String name) {super(name);}protected void setUp() {expectedWheels = 4;myCar = new Car();}public static Test suite() {/* * the type safe way *TestSuite suite= new TestSuite();suite.addTest(new testCar("Car.getWheels") { protected void runTest() { testGetWheels(); }});return suite;*//* * the dynamic way */return new TestSuite(testCar.class);}public void testGetWheels() {assertEquals(expectedWheels, myCar.getWheels());}}改版后的testCar已经面目全非。先让我们了解这些改动都是什么含义,再看如何执行这个测试。
[Windows] d:>java junit.textui.TestRunner testCar[Unix] % java junit.textui.TestRunner testCar别担心你要敲的字符量,以后在IDE中,只要点几下鼠标就成了。运行结果应该如下所示,表明执行了一个测试,并通过了测试:
.Time: 0OK (1 tests)如果我们将Car.getWheels()中返回的的值修改为3,模拟出错的情形,则会得到如下结果:
.FTime: 0There was 1 failure:1) testGetWheels(testCar)junit.framework.AssertionFailedError: expected:<4> but was:<3>at testCar.testGetWheels(testCar.java:37)FAILURES!!!Tests run: 1,Failures: 1,Errors: 0注意:Time上的小点表示测试个数,如果测试通过则显示OK。否则在小点的后边标上F,表示该测试失败。注意,在模拟出错的测试中,我们会得到详细的测试报告“expected:<4> but was:<3>”,这足以告诉我们问题发生在何处。下面就是你调试,测试,调试,测试...的过程,直至得到期望的结果。
……