# 第九章 單元測試 學習筆記 ###### tags: `讀書會` ## 整潔測試的要點: 1. 可讀性 2. 具有建造-操作-檢查的結構 (建立測試資料、操作測試資料、是否產生預期結果) ## 與產品程式的不同 * 以下測試的"HBchL",大寫字母代表"開啟",小寫字母代表關閉,雖然這違反思維轉換準則,但在測試中是適用的。 ```csharp= [TestMethod()] public void turnOnLoTempAlarmAtThreshold(){ wayTooCold(); assertEquals("HBchL", hw.GetState()); } ``` ```csharp= public string GetState(){ string state = ""; state += heater ? "H" : "h"; state += blower ? "B" : "b"; state += cooler ? "C" : "c"; state += hiTempAlarm ? "A" : "a"; state += loTempAlarm ? "L" : "l"; return state; } ``` ## 一個測試一個概念 * 雖然不用到一個測試一個assert這麼嚴謹,但assert還是要盡量減少。 * 一個測試一個概念 * Listing 9-8可改寫成 ```csharp= [DynamicData(nameof(GetDate), DynamicDataSourceType.Method)] [DataTestMethod()] public void TestAddMonths(int addMonths, DateModel expect){ SerialDate d1 = SerialDate.CreateInstance(31, 5, 2004); SerialDate d2 = SerialDate.AddMonths(addMonths, d1); assertEquals(expect.Day, d2.getDayOfMonth()); assertEquals(expect.Month, d2.getMonth()); assertEquals(expect.Year, d2.getYYYY()); } public static IEnumerable<object[]> GetDate(){ yield return new object[] {1, new DateModel{ 30, 6, 2004}}; yield return new object[] {2, new DateModel{ 31, 7, 2004}}; yield return new object[] {1, new DateModel{ 30, 7, 2004}}; } ``` ## FIRST法則 * Fast(快速): 他們要能被快速的運行。 * Independent(獨立): 測試程式不應該相互依賴。 * Repeatable(可重複性): 測試程式應該可以在任何環境中重複執行。 * Self-Validating(自我驗證): 測試程式應該輸出布林值。 * Timely(及時): 單元測試要恰好在使其通過的產品之前不久撰寫。