引言
JUnit 4 初体验
图1 为项目添加 JUnit 库
请注意 JDK 的版本
图2 修改项目源代码目录
- package
com.ai92.cooljunit; -
- import
java.util.regex.Matcher; - import
java.util.regex.Pattern; -
-
- public
class WordDealUtil { -
-
-
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(); -
} - }
- 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); -
} - }
测试方法必须使用 public void 修饰,而且不能带有任何参数。
图3 JUnit 运行成功界面
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); -
} - }
- //修改后的方法wordFormat4DB
-
-
public static String wordFormat4DB(String name){ -
-
if(name == null){ -
return null; -
} -
-
Pattern p = Pattern.compile("[A-Z]"); -
Matcher m = p.matcher(name); -
StringBuffer sb = new StringBuffer(); -
-
while(m.find()){ -
if(m.start() != 0) -
m.appendReplacement(sb, ("_"+m.group()).toLowerCase()); -
} -
return m.appendTail(sb).toString().toLowerCase(); -
}
图4 JUnit 运行失败界面
请牢记!