Java代碼 復制代碼
package com.ai92.cooljunit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 對名稱、地址等字符串格式的內(nèi)容進行格式檢查
* 或者格式化的工具類
*
* @author Ai92
*/
public class WordDealUtil {
/**
* 將Java對象名稱(每個單詞的頭字母大寫)按照
* 數(shù)據(jù)庫命名的習慣進行格式化
* 格式化后的數(shù)據(jù)為小寫字母,并且使用下劃線分割命名單詞
*
* 例如:employeeInfo 經(jīng)過格式化之后變?yōu)?employee_info
*
* @param name Java對象名稱
*/
public static String wordFormat4DB(String name){
Pattern p = Pattern.compile("[A-Z]");
Matcher m = p.matcher(name);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb, "_"+m.group());
}
return m.appendTail(sb).toString().toLowerCase();
}
}
它是否能按照預(yù)期的效果執(zhí)行呢?嘗試為它編寫 JUnit 單元測試代碼如下:
Java代碼 復制代碼
package com.ai92.cooljunit;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestWordDealUtil {
//測試wordFormat4DB正常運行的情況
@Test public void wordFormat4DBNormal(){
String target = "employeeInfo";
String result = WordDealUtil.wordFormat4DB(target);
assertEquals("employee_info", result);
}
}
很普通的一個類嘛!測試類 TestWordDealUtil 之所以使用“Test”開頭,完全是為了更好的區(qū)分測試類與被測試類。測試方法 wordFormat4DBNormal 調(diào)用執(zhí)行被測試方法 WordDealUtil.wordFormat4DB,以判斷運行結(jié)果是否達到設(shè)計預(yù)期的效果。需要注意的是,測試方法 wordFormat4DBNormal 需要按照一定的規(guī)范書寫:
測試方法必須使用注解 org.junit.Test 修飾。
測試方法必須使用 public void 修飾,而且不能帶有任何參數(shù)。
測試方法中要處理的字符串為“employeeInfo”,按照設(shè)計目的,處理后的結(jié)果應(yīng)該為“employee_info”。assertEquals 是由 JUnit 提供的一系列判斷測試結(jié)果是否正確的靜態(tài)斷言方法(位于類 org.junit.Assert 中)之一,我們使用它將執(zhí)行結(jié)果 result 和預(yù)期值“employee_info”進行比較,來判斷測試是否成功。
看看運行結(jié)果如何。在測試類上點擊右鍵,在彈出菜單中選擇 Run As JUnit Test。運行結(jié)果如下圖所示:
圖3 JUnit 運行成功界面
綠色的進度條提示我們,測試運行通過了。但現(xiàn)在宣布代碼通過了單元測試還為時過早。記。耗膯卧獪y試代碼不是用來證明您是對的,而是為了證明您沒有錯。因此單元測試的范圍要全面,比如對邊界值、正常值、錯誤值得測試;對代碼可能出現(xiàn)的問題要全面預(yù)測,而這也正是需求分析、詳細設(shè)計環(huán)節(jié)中要考慮的。顯然,我們的測試才剛剛開始,繼續(xù)補充一些對特殊情況的測試:
Java代碼 復制代碼
public class TestWordDealUtil {
……
//測試 null 時的處理情況
@Test public void wordFormat4DBNull(){
String target = null;
String result = WordDealUtil.wordFormat4DB(target);
assertNull(result);
}
//測試空字符串的處理情況
@Test public void wordFormat4DBEmpty(){
String target = "";
String result = WordDealUtil.wordFormat4DB(target);
assertEquals("", result);
}
//測試當首字母大寫時的情況
@Test public void wordFormat4DBegin(){
String target = "EmployeeInfo";
String result = WordDealUtil.wordFormat4DB(target);
assertEquals("employee_info", result);
}
//測試當尾字母為大寫時的情況
@Test public void wordFormat4DBEnd(){
String target = "employeeInfoA";
String result = WordDealUtil.wordFormat4DB(target);
assertEquals("employee_info_a", result);
}
//測試多個相連字母大寫時的情況
@Test public void wordFormat4DBTogether(){
String target = "employeeAInfo";
String result = WordDealUtil.wordFormat4DB(target);
assertEquals("employee_a_info", result);
}
}