![](https://csdnimg.cn/release/download_crawler_static/86335018/bg4.jpg)
*
* 例如:employeeInfo 经过格式化之后变为 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();
}
}
它是否能按照预期的效果执行呢?尝试为它编写 JUnit 单元测试代码如下:
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”开头,完全是为了更好的区分测试类
与被测试类。测试方法 wordFormat4DBNormal 调用执行被测试方法
WordDealUtil.wordFormat4DB,以判断运行结果是否达到设计预期的效果。需要注意的是,测试方法
wordFormat4DBNormal 需要按照一定的规范书写:
1. 测试方法必须使用注解 org.junit.Test 修饰。
2. 测试方法必须使用 public void 修饰,而且不能带有任何参数。
测试方法中要处理的字符串为“employeeInfo”,按照设计目的,处理后的结果应该为“employee_info”。
assertEquals 是由 JUnit 提供的一系列判断测试结果是否正确的静态断言方法(位于类