背景:當我們寫完一個類的時候,需要對類的某些方法進行測試。我以前的做法是在類的main函數中,new一個類的實例,然后調用類的方法進行測試。當需要測試的方法越來越較多的時候,main函數也在逐漸的變大,最后連自己都糊涂了。這時候就需要junit了。
編碼原則:
        從技術上強制你先考慮一個類的功能,也就是這個類提供給外部的接口,而不至于太早陷入它的細節。這是面向對象提倡的一種設計原則。
如果你要寫一段代碼:
1. 先用 junit 寫測試,然后再寫代碼
2. 寫完代碼,運行測試,測試失敗
3. 修改代碼,運行測試,直到測試成功
編寫步驟:如下圖

測試代碼:
package yhp.test.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()    {//JUnit的TestRunner會調用suite方法來確定有多少個測試可以執行
        return new TestSuite(TestCar.class);
    }
    public void testGetWheels(){//以test開頭,注意命名
        assertEquals(expectedWheels, myCar.getWheels());
    }
}

以下是通過eclipse自帶的junit工具產生的代碼:
package yhp.test.junit;
import junit.framework.TestCase;
public class TestCar2 extends TestCase {
    protected int expectedWheels;
    protected Car myCar;
    public static void main(String[] args) {
        junit.textui.TestRunner.run(TestCar2.class);//TestCar是個特殊suite的靜態方法
    }
    protected void setUp() throws Exception {
        super.setUp();
        expectedWheels = 4;
        myCar = new Car();
    }
    protected void tearDown() throws Exception {
        super.tearDown();
    }
    public TestCar2(String arg0) {
        super(arg0);
    }
    public final void testGetWheels() {
        assertEquals(expectedWheels, myCar.getWheels());
    }
}

當有多個測試類的時候,系統能進行統一測試,這時可以利用TestSuite來實現。可以將TestSuite看作是包裹測試的一個容器。
通過eclipse自帶的工具生成的代碼如下:
package yhp.test.junit;
import junit.framework.Test;
import junit.framework.TestSuite;

public class AllTests {
     public static Test suite() {
        TestSuite suite = new TestSuite("Test for yhp.test.junit");
        //$JUnit-BEGIN$
        suite.addTest(TestCar.suite());         //調用的方法,參數不一樣,實際是一致的。
        suite.addTestSuite(TestCar2.class);  //
        //$JUnit-END$
        return suite;
    }
}