×

maven springboot SpringBoot jacoco surefire junit

junit单元测试使用surefire和jacoco生成结果

我的笔记 我的笔记 发表于2024-06-03 13:38:12 浏览264 评论0

抢沙发发表评论

项目结构如图

版本情况,spring boot-2.5.2

image.png

第一步:首先父工程pomx.xml添加以下插件依赖:

<build>
    <plugins>
       <plugin>
          <groupId>org.jacoco</groupId>
          <artifactId>jacoco-maven-plugin</artifactId>
          <version>0.8.4</version>
          <executions>
             <execution>
                <id>prepare-agent</id>
                <goals>
                   <goal>prepare-agent</goal>
                </goals>
                <configuration>
                   <propertyName>surefireArgLine</propertyName>
                </configuration>
             </execution>
             <execution>
                <id>generate-code-coverage-report</id>
                <phase>test</phase>
                <goals>
                   <goal>report</goal>
                </goals>
             </execution>
          </executions>
       </plugin>
    </plugins>
</build>

第二步:子工程添加以下插件依赖:

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
	</dependency>
</dependencies>
<build>
    <plugins>
       <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
       </plugin>
       <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.1</version>
          <configuration>
             <target>1.8</target>
             <source>1.8</source>
             <encoding>UTF-8</encoding>
             <skip>false</skip>
          </configuration>
       </plugin>
       <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.2</version>
          <configuration>
             <skipTests>false</skipTests>
             <testFailureIgnore>true</testFailureIgnore>
             <forkMode>once</forkMode>
             <argLine>-Dfile.encoding=UTF-8 ${surefireArgLine}</argLine>
          </configuration>
       </plugin>
       <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-report-plugin</artifactId>
          <version>2.22.2</version>
          <executions>
             <execution>
                <id>report</id>
                <phase>test</phase><!-- 要绑定到的生命周期的阶段 -->
                <goals>
                   <goal>report</goal><!-- 要绑定的插件的目标 -->
                </goals>
             </execution>
          </executions>
       </plugin>
       <plugin>
          <groupId>org.jacoco</groupId>
          <artifactId>jacoco-maven-plugin</artifactId>
          <version>0.8.4</version>
          <executions>
             <execution>
                <id>report</id>
                <phase>test</phase>
                <goals>
                   <goal>report</goal>
                </goals>
             </execution>
          </executions>
       </plugin>
    </plugins>
</build>

第三步:正常编写测试类,单元测试类要写在src/test目录中,添加独立的配置文件

image.png

案例一:

package com.fyd;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.HashMap;
import java.util.Map;

@SpringBootTest(classes = UserApp.class)//此处写src/main中的启动类
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testJob() {
        Map<String, String> map = new HashMap<>();
        userMapper.test(map);
    }
}

案例二:

package com.fyd;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.Mockito.when;

@SpringBootTest(classes = UserApp.class)
public class UserJobHandleTest {

    private Authentication originalAuthentication;
    private MockMvc mockMvc;
    @Resource
    private WebApplicationContext webApplicationContext;
    @MockBean
    private RemoteLogService remoteLogService;

    @BeforeEach
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        //保存原始的认证信息
        originalAuthentication = SecurityContextHolder.getContext().getAuthentication();
        // 创建一个新的测试认证
        Authentication authentication = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
        // 设置到SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    @Test
    public void pkgApiTest() throws Exception {
        //mock模拟调用fegin接口
        when(remoteLogService.saveLog(sysLog, "Y")).thenReturn(R.ok(true));
        Map<String, String> map = new HashMap<>();
        map.put("n","test()");
        //模拟调用controller接口
        MvcResult mvcResult =  mockMvc.perform(
                        MockMvcRequestBuilders.post("/controlm/pkg")//构建一个post请求
                                .contentType(MediaType.APPLICATION_JSON_VALUE)
                                .content(JSON.toJSONString(map))
                )
                .andExpect(MockMvcResultMatchers.status().isOk())// 判断HTTP响应码
                .andReturn();
    }

    @AfterEach
    public void after(){
        SecurityContextHolder.getContext().setAuthentication(originalAuthentication);
    }
}






我的笔记博客版权我的笔记博客版权