一、集成测试

1、抽象类,用于请求头添加


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

import java.nio.charset.StandardCharsets;

// springboot web环测试,以随机端口执行,防止端口冲突
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@Slf4j
// 使用的配置环境
@ActiveProfiles("test")
public abstract class BaseIntegrationTest {

    @Autowired
    protected MockMvc mockMvc;

    @Autowired
    protected ObjectMapper objectMapper;

    protected HttpHeaders createRequestHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODYxNDY3OTIsInVzZXJuYW1lIjoiYWRtaW4ifQ.zKKxUOEOuHtrtmVtWnX9NvTNa0QSvYYtZJrnEf17erU");
        return headers;
    }

    protected ResultActions performRequest(MockHttpServletRequestBuilder requestBuilder) throws Exception {
        return mockMvc.perform(requestBuilder.headers(createRequestHeaders()));
    }

    protected MockHttpServletResponse getResponse(ResultActions resultActions) throws Exception {
        MockHttpServletResponse response = resultActions.andReturn().getResponse();
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        return response;
    }
}

2、测试接口或者方法


import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.ResultActions;

import java.math.BigDecimal;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

@Slf4j
public class BaseControllerIntegrationTest extends BaseIntegrationTest {

    @Autowired
    private ObjectMapper objectMapper;


    @Test
    public void testQueryPageList() throws Exception {
        // 准备测试数据
        int pageNo = 1;
        int pageSize = 10;

        // 发起请求
        ResultActions resultActions = performRequest(get("/base/list")
                .param("pageNo", String.valueOf(pageNo))
                .param("pageSize", String.valueOf(pageSize))
                .contentType(MediaType.APPLICATION_JSON));
        MockHttpServletResponse response = getResponse(resultActions);

        Assertions.assertEquals(200, response.getStatus());

        log.info("响应结果:"+response.getContentAsString());

        // 断言
        JSONObject result = JSONObject.parseObject(response.getContentAsString());
        Assertions.assertTrue(result.getBoolean("success"));
        Assertions.assertEquals(200, result.getIntValue("code"));
    }

    @Test
    public void testAdd() throws Exception {
        // 准备测试数据
        Base base = new Base();
        base.setNo("123"+ RandomUtil.randomInt(000_000,999_999));
        base.setName("测试");

        // 发起请求
        ResultActions resultActions = performRequest(post("/base/add")
                .content(objectMapper.writeValueAsString(base))
                .contentType(MediaType.APPLICATION_JSON));
        MockHttpServletResponse response = getResponse(resultActions);

        Assertions.assertEquals(200, response.getStatus());

        log.info("响应结果:"+response.getContentAsString());

        // 断言
        JSONObject result = JSONObject.parseObject(response.getContentAsString());
        Assertions.assertTrue(result.getBoolean("success"));
        Assertions.assertEquals(200, result.getIntValue("code"));

    }

    @Test
    public void testEdit() throws Exception {

        // 发起请求
        ResultActions resultActions = performRequest(get("/base/list")
                .contentType(MediaType.APPLICATION_JSON));
        MockHttpServletResponse response = getResponse(resultActions);

        Assertions.assertEquals(200, response.getStatus());

        log.info("响应结果:"+response.getContentAsString());

        // 断言
        JSONObject result = JSONObject.parseObject(response.getContentAsString());
        Assertions.assertTrue(result.getBoolean("success"));
        Assertions.assertEquals(200, result.getIntValue("code"));
        String firstBaseId = result.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");

        // 准备更新数据
        Base updatedBase = new Base();
        updatedBase.setId(firstBaseId);
        updatedBase.setName("编辑后的数据");

        // 断言
         resultActions = performRequest(post("/base/edit")
                .content(objectMapper.writeValueAsString(updatedBase))
                .contentType(MediaType.APPLICATION_JSON));
        response = getResponse(resultActions);

        // Assertions
        Assertions.assertEquals(200, response.getStatus());
        log.info("响应结果:" + response.getContentAsString());
        // 断言
        result = JSONObject.parseObject(response.getContentAsString());
        Assertions.assertTrue(result.getBoolean("success"));
        Assertions.assertEquals(200, result.getIntValue("code"));
    }
    
    @Test
    public void testDelete() throws Exception {
        // 准备测试数据
        ResultActions resultActions = performRequest(get("/base/list")
                .contentType(MediaType.APPLICATION_JSON));
        MockHttpServletResponse response = getResponse(resultActions);

        Assertions.assertEquals(200, response.getStatus());

        log.info("响应结果:"+response.getContentAsString());

        // 断言
        JSONObject result = JSONObject.parseObject(response.getContentAsString());
        Assertions.assertTrue(result.getBoolean("success"));
        Assertions.assertEquals(200, result.getIntValue("code"));
        String firstBaseId = result.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");

        // 发起删除请求
        ResultActions deleteResultActions = performRequest(post("/base/delete?id=" + firstBaseId)
                .contentType(MediaType.APPLICATION_JSON));
        MockHttpServletResponse deleteResponse = getResponse(deleteResultActions);

        // 删除断言
        Assertions.assertEquals(200, deleteResponse.getStatus());
        log.info("删除响应结果:" + deleteResponse.getContentAsString());
        // 断言
        result = JSONObject.parseObject(deleteResponse.getContentAsString());
        Assertions.assertTrue(result.getBoolean("success"));
        Assertions.assertEquals(200, result.getIntValue("code"));
    }





}

二、组件测试


import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

// 此处为需要导入的组件信息,类似spring的依赖注入
@Import(IncrementManage.class)
public class IncrementManageIntegrationTest extends BaseIntegrationTest {


    @Autowired
    private IncrementManage incrementManage;


    @Test
    public void getNextTest() {
        String key = "testKey";
        String value = incrementManage.getNext(key);
        Assertions.assertNotNull(value);
    }

    @Test
    public void getNextCompletionTest() {
        String key = "testKey";
        int num = 6;
        String value = incrementManage.getNextCompletion(key, num);
        Assertions.assertNotNull(value);
        Assertions.assertEquals(num, value.length());
    }


    @Test
    public void concurrentGetNextTest() throws InterruptedException {
        Set<String> sets = new HashSet<>();
        ExecutorService executorService = Executors.newFixedThreadPool(10); // Use a thread pool with 10 threads
        String key = "testKey";

        // Submit 100 tasks to the executor
        IntStream.range(0, 100).forEach(i -> executorService.submit(() -> {
            String value = incrementManage.getNext(key);
            Assertions.assertNotNull(value);
            sets.add(value);

        }));

        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES); // Wait for all tasks to complete
        System.out.println(sets.toString());
        System.out.println(sets.size()+"");
        Assertions.assertTrue(sets.size()==100);
    }

    @Test
    public void concurrentGetNextCompletionTest() throws InterruptedException {
        Set<String> sets = new HashSet<>();

        ExecutorService executorService = Executors.newFixedThreadPool(10); // Use a thread pool with 10 threads
        String key = "testKey";
        int num = 6;

        // Submit 100 tasks to the executor
        IntStream.range(0, 100).forEach(i -> executorService.submit(() -> {
            String value = incrementManage.getNextCompletion(key, num);
            Assertions.assertNotNull(value);
            Assertions.assertEquals(num, value.length());
            sets.add(value);

        }));

        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES); // Wait for all tasks to complete
        System.out.println(sets.toString());
        System.out.println(sets.size()+"");
        Assertions.assertTrue(sets.size()==100);
    }
}