走进Java接口测试之工具类库 Hutool

937 阅读8分钟

「这是我参与11月更文挑战的第30天,活动详情查看:2021最后一次更文挑战

一、背景

在 GitHub 上见到过很多开源的自动化框架内都自带了很多 Util 工具类,我们自己在开发自动化框架也必然需要用到工具类库,那么这样就会带来一些问题:

  • API的学习成本
  • 重复造轮子
  • 封装不完善带来的bug

那么,有没有比较好的通用轮子让我们直接使用呢?当然有,今天我们来介绍一下工具类库—Hutool

二、Hutool 简介

Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。 Hutool中的工具方法来自于每个用户的精雕细琢,它涵盖了Java开发底层代码中的方方面面,它既是大型项目开发中解决小问题的利器,也是小型项目中的效率担当; Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug。

以上是摘自官网的介绍,如果我们有需要用到某些工具方法的时候,不妨在Hutool里面找找。

官网地址:github.com/looly/hutoo…

三、Hutool 包含组件

一个Java基础工具类,对文件、流、加密解密、转码、正则、线程、XML等JDK方法进行封装,组成各种Util工具类,同时提供以下组件:

模块介绍
hutool-aopJDK动态代理封装,提供非IOC下的切面支持
hutool-bloomFilter布隆过滤,提供一些Hash算法的布隆过滤
hutool-cache简单缓存实现
hutool-core核心,包括Bean操作、日期、各种Util等
hutool-cron定时任务模块,提供类Crontab表达式的定时任务
hutool-crypto加密解密模块,提供对称、非对称和摘要算法封装
hutool-dbJDBC封装后的数据操作,基于ActiveRecord思想
hutool-dfa基于DFA模型的多关键字查找
hutool-extra扩展模块,对第三方封装(模板引擎、邮件、Servlet、二维码、Emoji、FTP、分词等)
hutool-http基于HttpUrlConnection的Http客户端封装
hutool-log自动识别日志实现的日志门面
hutool-script脚本执行封装,例如Javascript
hutool-setting功能更强大的Setting配置文件和Properties封装
hutool-system系统参数调用封装(JVM信息等)
hutool-jsonJSON实现
hutool-captcha图片验证码实现
hutool-poi针对POI中Excel和Word的封装
hutool-socket基于Java的NIO和AIO的Socket封装

可以根据需求对每个模块单独引入,也可以通过引入hutool-all方式引入所有模块。

四、安装

1、Maven

在项目的pom.xml的dependencies中加入以下内容:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.4.2</version>
</dependency>

2、Gradle

compile 'cn.hutool:hutool-all:5.4.2'

3、非Maven项目

点击以下任一链接,下载hutool-all-X.X.X.jar即可:

注意 Hutool 5.x支持 JDK8+,对 Android 平台没有测试,不能保证所有工具类或工具方法可用。 如果你的项目使用 JDK7,请使用 Hutool 4.x 版本

五、常用工具类

1、Convert

类型转换工具类,用于各种类型数据的转换。

@Test(description = "Convert使用:类型转换工具类")
public void covert() {
	int a = 1;
	String aStr = Convert.toStr(a);
	//转换为指定类型数组
	String[] b = {"1", "2", "3", "4"};
	Integer[] bArr = Convert.toIntArray(b);
	log.info(bArr.toString());

	//转换为日期对象
	String dateStr = "2020-09-17";
	Date date = Convert.toDate(dateStr);
	log.info(date.toString());

	//转换为列表
	String[] strArr = {"a", "b", "c", "d"};
	List<String> strList = Convert.toList(String.class, strArr);
	log.info(strList.toString());
}

运行结果:

[Ljava.lang.Integer;@4c0884e8
Thu Sep 17 00:00:00 CST 2020
[a, b, c, d]

2、DateUtil

日期时间工具类,定义了一些常用的日期时间操作方法。

@Test(description = "DateUtil使用:日期时间工具")
public void dateUtil() {
	//Date、long、Calendar之间的相互转换
	//当前时间
	Date date = DateUtil.date();
	log.info(date.toString());
	//Calendar转Date
	date = DateUtil.date(Calendar.getInstance());
	//时间戳转Date
	date = DateUtil.date(System.currentTimeMillis());
	//自动识别格式转换
	String dateStr = "2020-09-17";
	date = DateUtil.parse(dateStr);
	//自定义格式化转换
	date = DateUtil.parse(dateStr, "yyyy-MM-dd");
	//格式化输出日期
	String format = DateUtil.format(date, "yyyy-MM-dd");
	log.info(format.toString());
	//获得年的部分
	int year = DateUtil.year(date);
	//获得月份,从0开始计数
	int month = DateUtil.month(date);
	//获取某天的开始、结束时间
	Date beginOfDay = DateUtil.beginOfDay(date);
	Date endOfDay = DateUtil.endOfDay(date);
	//计算偏移后的日期时间
	Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
	//计算日期时间之间的偏移量
	long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);
}

运行结果:

2020-09-17 18:42:22
2020-09-17

3、StrUtil

字符串工具类,定义了一些常用的字符串操作方法。

@Test(description = "StrUtil使用:字符串工具")
public void strUtil() {
	//判断是否为空字符串
	String str = "test";
	StrUtil.isEmpty(str);
	StrUtil.isNotEmpty(str);
	//去除字符串的前后缀
	StrUtil.removeSuffix("a.jpg", ".jpg");
	StrUtil.removePrefix("a.jpg", "a.");
	//格式化字符串
	String template = "这只是个占位符:{}";
	String str2 = StrUtil.format(template, "我是占位符");
	log.info("/strUtil format:{}", str2);
}

运行结果:

/strUtil format:这只是个占位符:我是占位符

4、ClassPathResource

获取 classPath 下的文件,在 Tomcat 等容器下,classPath一般是 WEB-INF/classes

@Test(description = "ClassPath单一资源访问类:在classPath下查找文件")
public void classPath() throws IOException {
	//获取定义在src/main/resources文件夹中的配置文件
	ClassPathResource resource = new ClassPathResource("generator.properties");
	Properties properties = new Properties();
	properties.load(resource.getStream());
	log.info("/classPath:{}", properties);
}

运行结果:

/classPath:{jdbc.userId=root, jdbc.password=root, jdbc.driverClass=com.mysql.cj.jdbc.Driver, jdbc.connectionURL=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai}

5、ReflectUtil

Java反射工具类,可用于反射获取类的方法及创建对象。

@Test(description = "ReflectUtil使用:Java反射工具类")
public void reflectUtil() {
	//获取某个类的所有方法
	Method[] methods = ReflectUtil.getMethods(Dog.class);
	//获取某个类的指定方法
	Method method = ReflectUtil.getMethod(Dog.class, "getName");
	//使用反射来创建对象
	Dog dog = ReflectUtil.newInstance(Dog.class);
	//反射执行对象的方法
	ReflectUtil.invoke(dog, "setName","大黄");
	log.info(dog.getName());
}

Dog

Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Dog {
	private String name;
	private Float weight;
}

运行结果:

大黄

6、NumberUtil

数字处理工具类,可用于各种类型数字的加减乘除操作及判断类型。

@Test(description = "NumberUtil使用:数字处理工具类")
public void numberUtil() {
	double n1 = 1.234;
	double n2 = 1.234;
	double result;
	//对float、double、BigDecimal做加减乘除操作
	result = NumberUtil.add(n1, n2);
	result = NumberUtil.sub(n1, n2);
	result = NumberUtil.mul(n1, n2);
	result = NumberUtil.div(n1, n2);
	//保留两位小数
	BigDecimal roundNum = NumberUtil.round(n1, 2);
	String n3 = "1.234";
	//判断是否为数字、整数、浮点数
	NumberUtil.isNumber(n3);
	NumberUtil.isInteger(n3);
	NumberUtil.isDouble(n3);
}

7、BeanUtil

JavaBean的工具类,可用于Map与JavaBean对象的互相转换以及对象属性的拷贝。

@Test(description = "BeanUtil使用:JavaBean的工具类")
public void beanUtil() {
	Dog dog = new Dog();
	dog.setName("大黄");
	dog.setWeight(5.14f);

	//Bean转Map
	Map<String, Object> map = BeanUtil.beanToMap(dog);
	log.info("beanUtil bean to map:{}", map);
	//Map转Bean
	Dog mapDog = BeanUtil.mapToBean(map, Dog.class, false);
	log.info("beanUtil map to bean:{}", mapDog);
	//Bean属性拷贝
	Dog copyDog = new Dog();
	BeanUtil.copyProperties(dog, copyDog);
	log.info("beanUtil copy properties:{}", copyDog);
}

运行结果:

beanUtil bean to map:{name=大黄, weight=5.14}
beanUtil map to bean:Dog(name=大黄, weight=5.14)
beanUtil copy properties:Dog(name=大黄, weight=5.14)

8、CollUtil

集合操作的工具类,定义了一些常用的集合操作。

@Test(description = "CollUtil使用:集合工具类")
public void collUtil() {
	//数组转换为列表
	String[] array = new String[]{"a", "b", "c", "d", "e"};
	List<String> list = CollUtil.newArrayList(array);
	//join:数组转字符串时添加连接符号
	String joinStr = CollUtil.join(list, ",");
	log.info("collUtil join:{}", joinStr);
	//将以连接符号分隔的字符串再转换为列表
	List<String> splitList = StrUtil.split(joinStr, ',');
	log.info("collUtil split:{}", splitList);
	//创建新的Map、Set、List
	HashMap<Object, Object> newMap = CollUtil.newHashMap();
	HashSet<Object> newHashSet = CollUtil.newHashSet();
	ArrayList<Object> newList = CollUtil.newArrayList();
	//判断列表是否为空
	CollUtil.isEmpty(list);
	CollUtil.isNotEmpty(list);
}

运行结果:

collUtil join:a,b,c,d,e
collUtil split:[a, b, c, d, e]

9、MapUtil

Map操作工具类,可用于创建 Map 对象及判断 Map 是否为空。

@Test(description = "MapUtil使用:Map工具类")
public void mapUtil() {
	//将多个键值对加入到Map中
	Map<Object, Object> map = MapUtil.of(new String[][]{
			{"key1", "value1"},
			{"key2", "value2"},
			{"key3", "value3"}
	});
	//判断Map是否为空
	MapUtil.isEmpty(map);
	MapUtil.isNotEmpty(map);
}

10、SecureUtil

加密解密工具类,可用于 MD5 加密。

@Test(description = "SecureUtil使用:加密解密工具类")
public void secureUtil() {
	//MD5加密
	String str = "123456";
	String md5Str = SecureUtil.md5(str);
	log.info("secureUtil md5:{}", md5Str);
}

运行结果:

secureUtil md5:e10adc3949ba59abbe56e057f20f883e

11、CaptchaUtil

验证码工具类,可用于生成图形验证码。

@Test(description = "CaptchaUtil使用:图形验证码")
public void captchaUtil(HttpServletRequest request, HttpServletResponse response) {
	//生成验证码图片
	LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
	try {
		request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
		response.setContentType("image/png");//告诉浏览器输出内容为图片
		response.setHeader("Pragma", "No-cache");//禁止浏览器缓存
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		lineCaptcha.write(response.getOutputStream());
	} catch (IOException e) {
		e.printStackTrace();
	}
}

12、Validator

字段验证器,验证给定字符串是否满足指定条件,一般用在表单字段验证里。

@Test(description = "Validator使用:字段验证器")
public void validator() {
	//判断是否为邮箱地址
	boolean result = Validator.isEmail("zuozewei@hotmail.com");
	log.info("Validator isEmail:{}", result);
	//判断是否为手机号码
	result = Validator.isMobile("18911111111");
	log.info("Validator isMobile:{}", result);
	//判断是否为IPV4地址
	result = Validator.isIpv4("192.168.3.101");
	log.info("Validator isIpv4:{}", result);
	//判断是否为汉字
	result = Validator.isChinese("你好");
	log.info("Validator isChinese:{}", result);
	//判断是否为身份证号码(18位中国)
	result = Validator.isCitizenId("123456");
	log.info("Validator isCitizenId:{}", result);
	//判断是否为URL
	result = Validator.isUrl("http://www.7d.com");
	log.info("Validator isUrl:{}", result);
	//判断是否为生日
	result = Validator.isBirthday("2020-09-17");
	log.info("Validator isBirthday:{}", result);
}

运行结果:

Validator isEmail:true
Validator isMobile:true
Validator isIpv4:true
Validator isChinese:true
Validator isCitizenId:false
Validator isUrl:true
Validator isBirthday:true

13、JSONUtil

JSON 解析工具类,针对 JSONObject 和 JSONArray 的静态快捷方法集合。

@Test(description = "JSONUtil使用:JSON解析工具类")
public void jsonUtil() {
	Dog dog = new Dog();
	dog.setName("大黄");
	dog.setWeight(5.14f);

	//对象转化为JSON字符串
	String jsonStr = JSONUtil.parse(dog).toString();
	log.info("jsonUtil parse:{}", jsonStr);
	//JSON字符串转化为对象
	Dog dogBean = JSONUtil.toBean(jsonStr, Dog.class);
	log.info("jsonUtil toBean:{}", dogBean);
	List<Dog> dogList = new ArrayList<>();
	dogList.add(dog);
	String jsonListStr = JSONUtil.parse(dogList).toString();
	//JSON字符串转化为列表
	dogList = JSONUtil.toList(new JSONArray(jsonListStr), Dog.class);
	log.info("jsonUtil toList:{}", dogList);
}

运行结果:

jsonUtil parse:{"weight":5.14,"name":"大黄"}
jsonUtil toBean:Dog(name=大黄, weight=5.14)
jsonUtil toList:[Dog(name=大黄, weight=5.14)]

14、RandomUtil

随机工具类,RandomUtil 主要针对 JDK 中 Random 对象做封装。

@Test(description = "RandomUtil使用:随机工具类")
public void randomUtil() {
	int result;
	String uuid;
	//获得指定范围内的随机数
	result = RandomUtil.randomInt(1, 100);
	log.info("randomInt:{}",StrUtil.toString(result));
	//获得随机UUID
	uuid = RandomUtil.randomUUID();
	log.info("randomUUID:{}", uuid);
}

运行结果:

randomInt:9
randomUUID:8aec5890-72ab-4d72-a37d-d36acba83b58

15、DigestUtil

摘要算法工具类,支持常见摘要算法 MD2、MD5、SHA-1、SHA-256、SHA-384、SHA-512等。

@Test(description = "DigestUtil使用:摘要算法工具类")
public void digestUtil() {
	String password = "123456";
	//计算MD5摘要值,并转为16进制字符串
	String result = DigestUtil.md5Hex(password);
	log.info("DigestUtil md5Hex:{}", result);
	//计算SHA-256摘要值,并转为16进制字符串
	result = DigestUtil.sha256Hex(password);
	log.info("DigestUtil sha256Hex:{}", result);
	//生成Bcrypt加密后的密文,并校验
	String hashPwd = DigestUtil.bcrypt(password);
	boolean check = DigestUtil.bcryptCheck(password,hashPwd);
	log.info("DigestUtil bcryptCheck:{}", check);
}

运行结果:

DigestUtil md5Hex:e10adc3949ba59abbe56e057f20f883e
DigestUtil sha256Hex:8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
DigestUtil bcryptCheck:true

16、HttpUtil

Http客户端工具类,应对简单场景下Http请求的工具类封装,此工具封装了HttpRequest对象常用操作,可以保证在一个方法之内完成Http请求。

此模块基于JDK的HttpUrlConnection封装完成,完整支持https、代理和文件上传。

@Test(description = "HttpUtil使用:Http请求工具类")
public void httpUtil() {
	String response = HttpUtil.get("http://example.com/");
	log.info("HttpUtil get:{}", response);
}

运行结果:

2020-09-17 18:48:27.328  INFO 12004 --- [           main] com.zuozewei.demo.example.example        : HttpUtil get:<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

17、其他工具类

Hutool中的工具类很多,可以参考:www.hutool.cn/

六、小结

测试开发过程中要善于半开源,半代码的方式,节省开发时间,合理利用轮子,提高工作效率。

文章源码: github.com/zuozewei/bl…

参考资料: