#### 1.3 測試函數、用例和套件(1)
我們目前所構建的測試中已經有了幾個斷言,但是這里存在一個問題,由于測試失敗時assert函數只是簡單地拋出錯誤,所以我們沒法知道出錯的測試之后的測試是失敗還是成功。所以,如果我們想得到更細致的反饋,可以把測試組織成測試函數。如此一來,每個測試函數就只執行一個單元,但可以調用一個或多個斷言。如果我們還想要進一步得到完全的控制,還可以要求一個測試只測試某個單元的一個特定的行為。這意味著每個單個函數都會有多個簡練而明了的測試,而且,當它們被作為一個整體測試時也能提供很精確的反饋。
我們把一組相關的測試函數或方法叫做一個測試用例,就strftime函數來說,我們可以為整個函數設計一個測試用例,讓每個測試通過一個或多個斷言來測試函數的某個特定的行為。在更復雜的系統里,測試用例被進一步組織成測試套件。清單1.10列出了一個很簡單的testcase函數。它接受一個字符串名(name)和一個帶測試方法的對象。每個名字以“test”開頭的屬性都被當成測試方法來運行。
清單1.10 一個簡單的testcase函數
~~~
function testCase(name,tests){
assert.count =0;
var successful =0;
var testCount =0;
for (var test in tests){
if (!/^test/.test(test)){
continue;
}
testCount++;
try {
tests [test ]();
output(test,"#0c0");
successful++;
}catch (e){
output(test +"failed:"+e.message,"#c00");
}
}
var color =successful ==testCount ?"#0c0":"#c00";
output("<strong>"+testCount +"tests,"+
(testCount -successful)+"failures</strong>",
color);
}
~~~
清單1.11用testcase把strftime的測試重新組織成一個測試用例。
清單1.11 strftime測試用例
~~~
var date =new Date(2009,9,2);
testCase("strftime test",{
"test format specifier %Y":function (){
assert("%Y should return full year",
date.strftime("%Y")==="2009");
},
"test format specifier %m":function (){
assert("%m should return month",
date.strftime("%m")==="10");
},
"test format specifier %d":function (){
assert("%d should return date",
date.strftime("%d")==="02");
},
"test format specifier %y":function (){
assert("%y should return year as two digits",
date.strftime("%y")==="09");
},
"test format shorthand %F":function (){
assert("%F should act as %Y-%m-%d",
date.strftime("%F")==="2009-10-02");
}
});
~~~