背景:當(dāng)我們寫完一個類的時候,需要對類的某些方法進(jìn)行測試。我以前的做法是在類的main函數(shù)中,new一個類的實例,然后調(diào)用類的方法進(jìn)行測試。當(dāng)需要測試的方法越來越較多的時候,main函數(shù)也在逐漸的變大,最后連自己都糊涂了。這時候就需要junit了。
編碼原則:
        從技術(shù)上強制你先考慮一個類的功能,也就是這個類提供給外部的接口,而不至于太早陷入它的細(xì)節(jié)。這是面向?qū)ο筇岢囊环N設(shè)計原則。
如果你要寫一段代碼:
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(){  //進(jìn)行初始化任務(wù)
        expectedWheels = 4;
        myCar = new Car();
    }
    public static Test suite()    {//JUnit的TestRunner會調(diào)用suite方法來確定有多少個測試可以執(zhí)行
        return new TestSuite(TestCar.class);
    }
    public void testGetWheels(){//以test開頭,注意命名
        assertEquals(expectedWheels, myCar.getWheels());
    }
}

以下是通過eclipse自帶的junit工具產(chǎn)生的代碼:
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的靜態(tài)方法
    }
    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());
    }
}

當(dāng)有多個測試類的時候,系統(tǒng)能進(jìn)行統(tǒng)一測試,這時可以利用TestSuite來實現(xiàn)。可以將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());         //調(diào)用的方法,參數(shù)不一樣,實際是一致的。
        suite.addTestSuite(TestCar2.class);  //
        //$JUnit-END$
        return suite;
    }
}