基于Junit5+PowerMock的单元测试框架
前置
待测方法调用链庞大复杂;
待测方法内嵌其他类的静态、私有、final变量或者方法;
相关环境配置信息强依赖....
基于上面的场景,本文描述基于Junit+PowerMock+Mockito进行单元测试的方案中可能存在的小部分问题,PowerMock作为弥补Mockito无法mock类中静态、私有、final变量、方法及构造函数等不足的一扩展工具,在使用时还是可能会存在比较多坑:
PowerMock与Mockito的版本需要对应起来(具体见官网),否则可能出现:org.mockito.internal.handler.MockHandlerFactory.createMockHandler错误
缺点
junit本身不支持并行测试;工程中主要就Junit的如下4种场景的并行测试的实现进行描述:
单测试类的所有方法并行测试:
单测试类的单个方法并行测试:
多测试类的所有方法并行测试:
所有测试类一次执行
框架描述
主要是针对Junit框架、PowerMock框架以及部分其他三方工具进行整合创建的工具工程;囊括通用基本数据类型check、shell命令执行、性能监控、测试结果统计、报告生成、邮件通知等功能
工程目录结构如下:
├── lib
│ ├── cbbs-junit-ext-0.4.1.jar
│ ├── cpsuite-1.2.6.jar
│ ├── ganymed-ssh2-build210.jar
│ ├── qdox.jar
│ ├── system-rules-1.18.0.jar
│ └── testng-5.5.jar
├── pom.xml
├── report.html
├── src
│ ├── commons-logging.properties
│ ├── config.properties
│ ├── main
│ │ ├── constant
│ │ ├── junit5
│ │ ├── testng
│ │ ├── utcases
│ │ └── utils
│ └── test (对main中的工具类进行测试的测试类)
├── template
└── UnitTest.iml
备注:由于TestNG框架原生就支持并行、负载测试,所以在并发场景直接使用TestNG+Jmeter的框架
Junit5对应的pom依赖
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-console-standalone</artifactId>
<version>1.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.2.0</version>
</dependency>
针对支持并行测试的场景、监听终端日志捕获异常场景,需要添加如下pom:
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
<version>1.18.0</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-container-spi</artifactId>
<version>1.4.0.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-core</artifactId>
<version>1.4.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-container-spi</artifactId>
<version>1.4.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-container-test-api</artifactId>
<version>1.4.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.groboutils/groboutils-core -->
<dependency>
<groupId>net.sourceforge.groboutils</groupId>
<artifactId>groboutils-core</artifactId>
<version>5</version>
<scope>test</scope>
</dependency>
其中net.sourceforge.groboutils下的groboutils-core-5.jar需要手动添加到Global Libraries目录下
Junit5相关注解说明,官网实例,参见链接