每次写单元测试都要重复写一些方法、注解等,这里我写了一下测试的基类
(1) 记录测试方法运行的时间
(2)两个父类方法 print,可打印list和object对象
(3)一个属性 logger 记录日志
(4)DateUtil 是封装的一个处理时间的工具类
下面是代码:
DateUtil.java
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * 时间日期格式化 * * @author lixingwu */ public class DateUtil { /** * <p> 方法描述:毫秒转分钟秒数. </p> * <p> 创建时间:2017-12-08 14:07:01 </p> * <p> 创建作者:李兴武 </p> * * @param ms 毫秒数 * @return xx分钟xx秒 * @author "lixingwu" */ public static String formatTime(Long ms) { Integer ss = 1000; Integer mi = ss * 60; Integer hh = mi * 60; Integer dd = hh * 24; Long day = ms / dd; Long hour = (ms - day * dd) / hh; Long minute = (ms - day * dd - hour * hh) / mi; Long second = (ms - day * dd - hour * hh - minute * mi) / ss; Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss; StringBuilder sb = new StringBuilder(); if (day > 0) { sb.append(day).append("天"); } if (hour > 0) { sb.append(hour).append("小时"); } if (minute > 0) { sb.append(minute).append("分钟"); } if (second > 0) { sb.append(second).append("秒"); } if (milliSecond > 0) { sb.append(milliSecond).append("毫秒"); } return sb.toString(); } }
BaseSpringBootTest .java
import com.zhwlt.logistics.utils.DateUtil; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.CollectionUtils; import java.util.List; /** * 测试基类 */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public abstract class BaseSpringBootTest { protected Logger logger = LoggerFactory.getLogger(this.getClass()); private long time; public long getTime() { return time; } public void setTime(long time) { this.time = time; } @Before public void setUp() throws Exception { this.setTime(System.currentTimeMillis()); logger.info("==> 测试开始执行 <=="); } @After public void tearDown() throws Exception { logger.info("==> 测试执行完成,耗时:{} <==", DateUtil.formatTime(System.currentTimeMillis() - this.getTime())); } /** * 方法描述:打印list. * 创建时间:2018-10-11 00:23:28 */ <T> void print(List<T> list) { if (!CollectionUtils.isEmpty(list)) { list.forEach(System.out::println); } } void print(Object o) { System.out.println(o.toString()); } }
使用方法:
测试类继承 BaseSpringBootTest 即可,例如:
import org.junit.Test; import javax.annotation.Resource; /** * 异步任务 测试 */ public class AsyncServiceTest extends BaseSpringBootTest { @Resource private AsyncService asyncService; @Test public void AsyncMTest() { asyncService.AsyncM(); System.out.println("==> 测试异步任务"); } }