以前的时候(读大学时),我认为写单元测试太费事了。现在,我改变看法了。
工作中,为了提高Web开发的质量和效率,近期又为了保证自己的工具类等一系列可复用组件的质量,我煞费苦心地开始认真学习和撰写单元测试用例。
我现在已经厌倦了Debug程序,更讨厌Debug Web程序,太浪费时间了。
最近,线上的一个BM项目,出了个bug。浮点数相减,没有判断null,搞的我加班到9:30。
苦逼的码农啊。
下面,分享我的一个工具类和对应的单元测试用例。
有不对的地方,还望能告知我。大家共同进步。
/**
* 判断Collection(List和Set),Map等集合类型是否为空,是否含有空值。
* 判断String是否为空,参考ApacheCommonsLang-StringUtils。
*
* @author leiwen
*/
public class EmptyUtils {
/**
* 判断Collection(List和Set) 是否为空
*
* @param collection
* List或Set类型的集合
* @return 如果collection是 null或size=0,返回true;否则,返回false。
*/
public static boolean isEmpty(Collection< > collection) {
return collection == null || collection.size() == 0;
}
/**
* 判断map是否为空
*
* @param map
* 键值对数据类型
* @return 如果map是 null或size=0,返回true;否则,返回false。
*/
public static boolean isEmpty(Map< , > map) {
return map == null || map.size() == 0;
}
/**
* 判断一个数组是否为空。
*
* @param array
* 对象数组
* @return 如果数组为null或者数组元素个数为0,返回true;否则,返回false。
*/
public static boolean isEmpty(Object[] array) {
return array == null || array.length == 0;
}
/**
* 判断Collection(List和Set) 不为空
*
* @param collection
* List或Set类型的集合
* @return 如果collection不等于null且size>0,返回true;否则,返回false。
*/
public static boolean notEmpty(Collection< > collection) {
return !isEmpty(collection);
}
/**
* 判断map不为空
*
* @param map
* 键值对数据类型
* @return 如果map不为 null且size>0,返回true;否则,返回false。
*/
public static boolean notEmpty(Map< , > map) {
return !isEmpty(map);
}
/**
* 判断一个数组不为空。
*
* @param array
* 对象数组
* @return 如果数组为null或者数组元素个数为0,返回false;否则,返回true。
*/
public static boolean notEmpty(Object[] array) {
return !isEmpty(array);
}
}
package cn.fansunion.webcommon.platform;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
import org.junit.Test;
import cn.fansunion.common.util.EmptyUtils;
/**
*
*
* @author leiwen
*/
public class EmptyUtilsTest extends TestCase {
@Test
public static void testCollectionIsEmpty() {
List
boolean listWithPositiveSize = EmptyUtils.isEmpty(list);
assertFalse(listWithPositiveSize);
List
boolean listWithZeroSize = EmptyUtils.isEmpty(emptyList);
assertTrue(listWithZeroSize);
List
boolean nullEmpty = EmptyUtils.isEmpty(nullList);
assertTrue(nullEmpty);
Set
set.add(100);
boolean setWithPositiveSize = EmptyUtils.isEmpty(set);
assertFalse(setWithPositiveSize);
Set
assertTrue(EmptyUtils.isEmpty(nullSet));
Set
assertTrue(EmptyUtils.isEmpty(emptySet));
}
@Test
public static void testMapIsEmpty() {
Map
map.put("mapTest", "mapTestValue");
assertFalse(EmptyUtils.isEmpty(map));
Map
assertTrue(EmptyUtils.isEmpty(nullEmpt