JUnit4單元測試的兩種形式

特色:

  • JUnit 是一個開放的資源框架,用於編寫和運行測試。框架

  • 提供註釋來識別測試方法。eclipse

  • 提供斷言來測試預期結果。工具

  • 提供測試運行來運行測試。單元測試

  • JUnit 測試容許你編寫代碼更快,並能提升質量。開發工具

  • JUnit 優雅簡潔。沒那麼複雜,花費時間較少。測試

  • JUnit 測試能夠自動運行而且檢查自身結果並提供即時反饋。因此也沒有必要人工梳理測試結果的報告。ui

  • JUnit 測試能夠被組織爲測試套件,包含測試用例,甚至其餘的測試套件。spa

  • JUnit 在一個條中顯示進度。若是運行良好則是綠色;若是運行失敗,則變成紅色。.net

  • JUnit測試減小後期維護時間以及成本繼承

    導入JUnit4單元測試所需的jar包
    打開開發工具 eclipse|myeclipse -> 對應項目右擊 > Build Path > Add Library > JUnit
    > 選擇版本JUnit4 > Finish
    單元模塊測試——單個類
    一、使用@Test註解
    例子:
    import static org.junit.Assert.assertEquals;
    import org.junit.Test;
    public class Test01
    {
    final static String CH = "中國";
    @Test
    //(命名格式建議用test+方法名)
    public void testCode()
    throws Exception
    {
    assertEquals("中國", CH);
    }

    }

    二、extend TestCase類
    例子:
    import junit.framework.TestCase;
    public class Test01 extends TestCase
    {
    final static String CH = "中國";
    //(命名格式建議用test+方法名) //繼承TestCase,如命名方法沒有test做爲前綴則報錯
    public void testCode()
    throws Exception
    {
    assertEquals("中國", CH);
    }

    }

    單元模塊測試——多個類

    三、使用JUnitCore.runClasses(StudentTest01.class)返回Result類型;
       調用for (Failure failure : result.getFailures())進行遍歷

    例子:
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    public class TestRunner
    {

        public static void main(String[] args)
        {
            // TODO Auto-generated method stub
            Result result = JUnitCore.runClasses(StudentTest01.class);
            for (Failure failure : result.getFailures())
           
    {
                System.out.println(failure.toString());
            }
            // 測試過程當中是否成功
            System.out.println(result.wasSuccessful());
        }
    }

    四、使用註解 @RunWith、@Suite.SuiteClasses

    例子:
    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    @RunWith(Suite.class)
    @Suite.SuiteClasses({
        //測試類做爲參數,多個參數用逗號隔開
        StudentTest01.class, StudentTest02.class})
    public class AllTest
    {   }

    五、使用TestSuite類中的addTestSuite添加測試類、run(new TestResult())運行測試類

    例子:
    import junit.framework.TestResult;
    import junit.framework.TestSuite;
    public class AllTest
    {
        public static void main(String[] args)
        {
            TestSuite testSuite = new TestSuite();
            testSuite.addTestSuite(StudentTest01.class);
            testSuite.addTestSuite(StudentTest02.class);
            testSuite.run(new TestResult());

        }

    }


    參考連接:https://www.w3cschool.cn/junit/

相關文章
相關標籤/搜索