//執行測試的類(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: 0 OK (1 tests)如果我們將Car.getWheels()中返回的的值修改為3,模擬出錯的情形,則會得到如下結果:
.F Time: 0 There 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>”,這足以告訴我們問題發生在何處。下面就是你調試,測試,調試,測試...的過程,直至得到期望的結果。
原文轉自:http://www.anti-gravitydesign.com