一、idea 安装自动化生成插件jcode5
安装可能不成功,尝试多次安装;
安装成功后,重启idea,再次确认安装是否成功;
二、在需要生成单元测试代码的模块的pom中引入依赖
......
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
......
<!-- 单元测试 覆盖率 openclover -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
......
三、初始化单元测试类
大概需要添加单元测试代码的类,鼠标放在类名字出,按alt+insert,选择jcode5;
选择generate test class 初始化单元测试代码;
四、剔除无用import报错行
ctrl+alt+o
五、造数据,完善测试代码,使得覆盖率提升
1.有报错信息优先处理报错信息
2.若使用泛型类需要,处理泛型类T、 Map<K,V>、 ConsumerRecord<?, ?>、V.class等
3.完善打桩代码when
4.调整数据文件使测试代码可正常执行
5.存在逻辑复杂的测试方法时,且需要模拟多种数据时,可以在复制一个测试方法和测试数据文件
6.完善其他代码
7.执行mvn test 查看测试代码执行结果
六、修改特例
Map<K,V>可修改为
Map<String, Object>
对于模拟不来的,可以直接使用构造javabean的方式
测试目标类中 @Value注释的属性如何初始化
ReflectionTestUtils.setField(XXXService, "env", "prod");
测试目标类中静态类如何初始化
try(MockedStatic<ESUtils> theMock = Mockito.mockStatic(ESUtils.class)) {
theMock.when(() -> ESUtils.convertToSearchFieldsList(Mockito.any())).thenReturn(combineRule);
}
try(MockedStatic<HttpUtil> theMock = Mockito.mockStatic(HttpUtil.class)) {
theMock.when(() -> HttpUtil.get(anyString(), anyInt())).thenReturn("");
}