#14 开始整理Modules的单元测试,提高测试覆盖率,并顺手改进代码。

This commit is contained in:
Calvin
2012-05-05 23:39:31 +08:00
parent da2440535c
commit e819fbcefd
50 changed files with 271 additions and 451 deletions
@@ -27,9 +27,6 @@ import com.google.common.collect.Lists;
*/
public class BeanValidators {
private BeanValidators() {
}
/**
* 调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException.
*/
@@ -16,7 +16,7 @@ import com.google.common.collect.Lists;
* 简单封装Dozer, 实现深度转换Bean<->Bean的Mapper.实现:
*
* 1. 持有Mapper的单例.
* 2. 泛型返回值转换.
* 2. 返回值类型转换.
* 3. 批量转换Collection中的所有对象.
* 4. 区分创建新的B对象与将对象A值复制到已存在的B对象两种函数.
*
@@ -29,9 +29,6 @@ public class BeanMapper {
*/
private static DozerBeanMapper dozer = new DozerBeanMapper();
private BeanMapper() {
}
/**
* 基于Dozer转换对象的类型.
*/
@@ -3,9 +3,6 @@ package org.springside.modules.orm.jpa;
import org.hibernate.Hibernate;
public class Jpas {
private Jpas() {
}
public static void initLazyProperty(Object proxyed) {
Hibernate.initialize(proxyed);
@@ -17,9 +17,6 @@ public class RsResponse {
private static Logger logger = LoggerFactory.getLogger(RsResponse.class);
private RsResponse() {
}
/**
* 创建WebApplicationException并记打印日志, 使用标准状态码与自定义信息并记录错误信息.
*/
@@ -37,9 +37,6 @@ public class Cryptos {
private static SecureRandom random = new SecureRandom();
private Cryptos() {
}
//-- HMAC-SHA1 funciton --//
/**
* 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
@@ -11,6 +11,7 @@ import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import org.apache.commons.lang.Validate;
import org.springside.modules.utils.Exceptions;
/**
@@ -27,9 +28,6 @@ public class Digests {
private static SecureRandom random = new SecureRandom();
private Digests() {
}
/**
* 对输入字符串进行sha1散列.
*/
@@ -74,9 +72,8 @@ public class Digests {
* @param numBytes byte数组的大小
*/
public static byte[] generateSalt(int numBytes) {
if (numBytes <= 0) {
throw new IllegalArgumentException("numBytes argument must be a positive integer (1 or larger)");
}
Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
byte[] bytes = new byte[numBytes];
random.nextBytes(bytes);
return bytes;
@@ -22,9 +22,6 @@ import org.apache.commons.lang3.StringUtils;
*/
public class Collections3 {
private Collections3() {
}
/**
* 返回a-b的集合.
*/
@@ -19,7 +19,7 @@ import org.apache.commons.lang3.StringEscapeUtils;
*
* 1.Commons-Codec的 hex/base64 编码
* 2.自制的base62 编码
* 3.Commons-Lang的xml/html/csv escape
* 3.Commons-Lang的xml/html escape
* 4.JDK提供的URLEncoder
*
* @author calvin
@@ -29,9 +29,6 @@ public class Encodes {
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
private Encodes() {
}
/**
* Hex编码.
*/
@@ -46,7 +43,7 @@ public class Encodes {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw new IllegalStateException("Hex Decoder exception", e);
throw Exceptions.unchecked(e);
}
}
@@ -110,20 +107,6 @@ public class Encodes {
return StringEscapeUtils.unescapeXml(xmlEscaped);
}
/**
* Csv 转码.
*/
public static String escapeCsv(String csv) {
return StringEscapeUtils.escapeCsv(csv);
}
/**
* Csv 解码.
*/
public static String unescapeCsv(String csvEscaped) {
return StringEscapeUtils.unescapeCsv(csvEscaped);
}
/**
* URL 编码, Encode默认为UTF-8.
*/
@@ -15,9 +15,6 @@ import java.io.StringWriter;
*/
public class Exceptions {
private Exceptions() {
}
/**
* 将CheckedException转换为UncheckedException.
*/
@@ -10,23 +10,17 @@ import org.springframework.core.io.Resource;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkers {
private FreeMarkers() {
}
public static String rendereString(String templateString, Map<String, ?> model) {
try {
StringWriter result = new StringWriter();
Template t = new Template("name", new StringReader(templateString), new Configuration());
t.process(model, result);
return result.toString();
} catch (IOException e) {
throw new RuntimeException("Freemarker template error", e);
} catch (TemplateException e) {
throw new RuntimeException("Freemarker template error", e);
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
@@ -35,19 +29,15 @@ public class FreeMarkers {
StringWriter result = new StringWriter();
template.process(model, result);
return result.toString();
} catch (IOException e) {
throw new RuntimeException("Freemarker template not exist", e);
} catch (TemplateException e) {
throw new RuntimeException("Freemarker template error", e);
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
public static Configuration buildConfiguration(String directory) throws IOException {
Configuration cfg = new Configuration();
Resource path = new DefaultResourceLoader().getResource(directory);
cfg.setDirectoryForTemplateLoading(path.getFile());
return cfg;
}
}
@@ -17,9 +17,6 @@ public class Identities {
private static SecureRandom random = new SecureRandom();
private Identities() {
}
/**
* 封装JDK自带的UUID, 通过Random数字生成, 中间有-分割.
*/
@@ -63,14 +63,19 @@ public class PropertiesLoader {
}
/**
* 取出Property,但以System的Property优先.
* 取出Integer类型的Property,但以System的Property优先.如果都為Null則返回0.
*/
public Integer getInteger(String key) {
return Integer.valueOf(getProperty(key));
String strResult = getProperty(key);
if (strResult != null) {
return Integer.valueOf(strResult);
} else {
return 0;
}
}
/**
* 取出Property,但以System的Property优先.
* 取出Integer类型的Property,但以System的Property优先.如果都為Null則返回Default值.
*/
public Integer getInteger(String key, Integer defaultValue) {
String strResult = getProperty(key);
@@ -82,14 +87,14 @@ public class PropertiesLoader {
}
/**
* 取出Property,但以System的Property优先.
* 取出Boolean类型的Property,但以System的Property优先.如果都為Null則返回false.
*/
public Boolean getBoolean(String key) {
return Boolean.valueOf(getProperty(key));
}
/**
* 取出Property,但以System的Property优先.
* 取出Boolean类型的Property,但以System的Property优先.如果都為Null則返回Default值.
*/
public Boolean getBoolean(String key, boolean defaultValue) {
String strResult = getProperty(key);
@@ -98,7 +103,6 @@ public class PropertiesLoader {
} else {
return defaultValue;
}
}
/**
@@ -29,9 +29,6 @@ public class Reflections {
private static Logger logger = LoggerFactory.getLogger(Reflections.class);
private Reflections() {
}
/**
* 调用Getter方法.
*/
@@ -41,7 +38,9 @@ public class Reflections {
}
/**
* 调用Setter方法.使用value的Class来查找Setter方法.
* 调用Setter方法,如果屬性是原始類型,需要使用帶propertyType的版本.
*
* @see #invokeSetter(Object, String, Object, Class)
*/
public static void invokeSetter(Object obj, String propertyName, Object value) {
invokeSetter(obj, propertyName, value, null);
@@ -50,10 +49,11 @@ public class Reflections {
/**
* 调用Setter方法.
*
* @param propertyType 用于查找Setter方法,为空时使用value的Class替代.
* @param propertyType 作为setter方法的输入参数类型查找Setter方法,为Null时使用value的Class替代.
*/
public static void invokeSetter(Object obj, String propertyName, Object value, Class<?> propertyType) {
Class<?> type = propertyType != null ? propertyType : value.getClass();
String setterMethodName = "set" + StringUtils.capitalize(propertyName);
invokeMethod(obj, setterMethodName, new Class[] { type }, new Object[] { value });
}
@@ -15,9 +15,6 @@ import java.util.concurrent.TimeUnit;
*/
public class Threads {
private Threads() {
}
/**
* sleep等待,单位为毫秒,忽略InterruptedException.
*/
@@ -39,9 +39,6 @@ public class Servlets {
//-- 常用数值定义 --//
public static final long ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
private Servlets() {
}
/**
* 设置客户端缓存过期时间 的Header.
*/
@@ -42,6 +42,10 @@ public class BeanValidatorsTest extends SpringContextTestCase {
String result = StringUtils.join(BeanValidators.extractPropertyAndMessage(violations, " "), ",");
assertTrue(StringUtils.contains(result, "email not a well-formed email address"));
assertTrue(StringUtils.contains(result, "name may not be empty"));
result = StringUtils.join(BeanValidators.extractMessage(violations), ",");
assertTrue(StringUtils.contains(result, "not a well-formed email address"));
assertTrue(StringUtils.contains(result, "may not be empty"));
}
@Test
@@ -62,9 +66,9 @@ public class BeanValidatorsTest extends SpringContextTestCase {
private static class Customer {
String name;
private String name;
String email;
private String email;
@NotBlank
public String getName() {
@@ -51,17 +51,4 @@ public class EncodesTest {
assertEquals("1&gt;2", result);
assertEquals(input, Encodes.unescapeHtml(result));
}
@Test
public void csv() {
String input = "haha,kaka";
String result = Encodes.escapeCsv(input);
System.out.println(result);
assertEquals(input, Encodes.unescapeCsv(result));
//
input = "\"ha\"ka";
result = Encodes.escapeCsv(input);
System.out.println(result);
assertEquals(input, Encodes.unescapeCsv(result));
}
}
@@ -0,0 +1,5 @@
package org.springside.modules.utils;
public class ExceptionsTest {
}
@@ -24,6 +24,21 @@ public class PropertiesLoaderTest {
public void notExistProperty() throws IOException {
Properties p = new PropertiesLoader("classpath:/notexist.properties").getProperties();
assertNull(p.getProperty("notexist"));
assertEquals("defaultValue", p.getProperty("notexist", "defaultValue"));
}
@Test
public void integerAndBooleanProperty() {
PropertiesLoader p = new PropertiesLoader("classpath:/test1.properties", "classpath:/test2.properties");
assertEquals(new Integer(1), p.getInteger("p1"));
assertEquals(new Integer(0), p.getInteger("notExist"));
assertEquals(new Integer(100), p.getInteger("notExist", 100));
assertEquals(new Boolean(true), p.getBoolean("p4"));
assertEquals(new Boolean(false), p.getBoolean("notExist"));
assertEquals(new Boolean(true), p.getBoolean("notExist", true));
}
@Test
@@ -31,5 +46,6 @@ public class PropertiesLoaderTest {
System.setProperty("p1", "sys");
PropertiesLoader pl = new PropertiesLoader("classpath:/test1.properties", "classpath:/test2.properties");
assertEquals("sys", pl.getProperty("p1"));
System.clearProperty("p1");
}
}
@@ -34,6 +34,10 @@ public class ReflectionsTest {
bean = new TestBean();
Reflections.invokeSetter(bean, "publicField", 10, int.class);
assertEquals(10 + 1, bean.inspectPublicField());
//非原始類型,可省略類型參數
Reflections.invokeSetter(bean, "name", "foo");
assertEquals("foo", bean.name);
}
@Test
@@ -88,14 +92,22 @@ public class ReflectionsTest {
/** 有getter/setter的field */
private int publicField = 1;
private String name;
//通過getter函數會比屬性值+1
public int getPublicField() {
return publicField + 1;
}
//通過setter函數會被比輸入值加1
public void setPublicField(int publicField) {
this.publicField = publicField + 1;
}
public void setName(String name) {
this.name = name;
}
public int inspectPrivateField() {
return privateField;
}
@@ -1,2 +1,3 @@
p1=1
p2=2
p2=2
p4=true