在中提到了代碼覆蓋率,我很久沒有去書店了,不知道是不是出了新的版本,覺得書里面關于代碼覆蓋率方面的知識有些地方沒有講,在這里補充一下。先回顧一下如何
查看代碼覆蓋率
創建一個C#工程WildChar(無所謂是類型庫工程還是命令行程序工程),假設我們要寫一個將字符串按單詞成對反轉的程序。將下面的代碼貼到工程的一個cs文件中:
Program.cs
public static string ReverseStringPair(string input) { if (string.IsNullOrEmpty(input)) throw new ArgumentNullException("input"); char[] result = new char[input.Length]; int resultIter = 0; ReverseStringPairImp(input, 0, result, resultIter); return new string(result); } private static void ReverseStringPairImp(string input, int inputIter, char[] result, int resultIter) { // skip white space while (inputIter < input.Length && input[inputIter] == ' ') inputIter++; int[] indics = new int[2] { inputIter, // first word begin index, 0 // second word begin index }; for (; inputIter < input.Length; ++inputIter) { if (input[inputIter] == ' ') { if (indics[1] == 0) indics[1] = -1; else if (indics[1] > 0) break; } else if (input[inputIter] != ' ' && indics[1] == -1) indics[1] = inputIter; } // copy second word, inputIter points to the end of second word if (indics[1] > 0) { for (int i = indics[1]; i < inputIter; ++i) result[resultIter++] = input[i]; indics[1]--; // copy white space while (indics[1] >= 0 && input[indics[1]] == ' ') indics[1]--; result[resultIter++] = ' '; } else indics[1] = input.Length - 1; // copy the first word for (int i = indics[0]; i <= indics[1]; ++i) result[resultIter++] = input[i]; // next pair if (inputIter < input.Length) { result[resultIter++] = ' '; ReverseStringPairImp(input, inputIter, result, resultIter); } } |
把鼠標放在ReverseStringPair函數的聲明上(或者說第一行),點擊右鍵,并且選擇“創建單元測試”命令,一切按照默認的設置選擇“確定”按鈕,創建一個測試工程。
在新創建的測試工程自動添加的programtest.cs(因為類名叫做program)文件里,添加一個新測試用例:
Programtest.cs
[TestMethod()] public void ReverseStringPairTest() { string input = "ab cd ef gh"; string expected = "cd ab gh ef"; string actual = Program.ReverseStringPair(input); Assert.AreEqual(expected, actual); } |
單元測試用例創建好了以后,點擊工具欄里面的“Run Tests in Current Context”,就能看到測試結果了,如下圖所示:
啟用代碼覆蓋率測試
只執行單元測試是不能檢查代碼覆蓋情況的—即你創建的測試用例總共覆蓋了多少行源代碼。為什么需要特意開啟代碼覆蓋率測試是有原因的,這個在文章的最后會講到。
1. 在“解決方案瀏覽器(Solution Explorer)”里,雙擊“localtestrun.testrunconfig”文件。
2. 在彈出的“localtestrun.testrunconfig”窗口里,雙擊“代碼覆蓋率(Code Coverage)”。
3. 里面會列出好幾個文件,有.dll ,也會有.exe。勾選你要測試代碼覆蓋率的程序,比如說你要測試WildChar工程—也就是我們的產品代碼的代碼覆蓋率,請勾選 WildChar.exe。不要勾選包含測試用例的那個dll文件,因為我們對測試代碼本身的覆蓋率沒有任何興趣。結果如下圖所示:
4. 點擊“應用(Apply)”關閉窗口。
在重新運行一下所有的測試用例,點擊測試結果窗口工具欄最右邊的按鈕,查看代碼覆蓋率情況,如下圖所示:
原文轉自:http://www.uml.org.cn/Test/201306262.asp