SpringBoot MockMvcTest - api单元测试

1,696 阅读1分钟

JUnit 简介

JUnit是一款Java语言的单元测试框架,目前大多数Java开发环境都已经支持它了。JUnit测试也就是所谓的白盒测试,在程序员知道程序内部逻辑的基础上进行的测试,使用JUnit能让我们快速地完成单元测试。Spring Boot Test将JUnit和其他测试框架结合起来,提供了便捷高效的测试手段,目前Spring Boot 2.7版本采用的是JUnit 5。

有时候我们接口开发完了,需要在本地进行单元测试,通过MockMvc来实现是个不错的选择,比如,现在有一个JedisTestController:

@Slf4j
@RestController
@RequestMapping("/jedis")
public class JedisController {

    private static final int time_out = 360;

    @PostMapping("/jedisUtilsSetTest")
    public String jedisUtilsSetTest() {

        String stringKey = "stringKey";
        String objectKey = "objectKey";
       
        JedisUtils.getInstance().set(stringKey, "value", time_out);

        AgentIdentityConfig agentIdentityConfig = new AgentIdentityConfig();
        agentIdentityConfig.setId("1");
        agentIdentityConfig.setAgentId("2");
        agentIdentityConfig.setLanguages("232");
        agentIdentityConfig.setRegSwitchStartTime(new Date());
        agentIdentityConfig.setRegSwitchEndTime(new Date());
        agentIdentityConfig.setDefaultPoints(0);
        agentIdentityConfig.setIssuerShortName("2332");
        agentIdentityConfig.setChargePrice(new BigDecimal("0"));
        agentIdentityConfig.setRedeemTimes(0);
        agentIdentityConfig.setCreateTime(new Date());
        agentIdentityConfig.setUpdateTime(new Date());
        JedisUtils.getInstance().setObject(objectKey, agentIdentityConfig, time_out);

        return "jedisUtilsSetTest";
    }


    @GetMapping("/jedisUtilsGetTest")
    public JSONObject jedisUtilsGetTest() {
        JSONObject result = new JSONObject();

        String stringKey = "stringKey";
        String objectKey = "objectKey";
       
        String stringValue = JedisUtils.getInstance().get(stringKey);
        System.out.println("stringValue: " + stringValue);

        AgentIdentityConfig objectValue = (AgentIdentityConfig) JedisUtils.getInstance().getObject(objectKey);
        System.out.println("objectValue: " + objectValue);

        result.put("stringValue", stringValue);
        result.put("objectValue", objectValue);
        return result;
    }
}

在SpringBoot test文件夹下创建JedisMockTest测试类

import org.junit.Test;
import org.junit.jupiter.api.Order;
import org.junit.runner.RunWith;
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.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import java.nio.charset.StandardCharsets;

/**
 * @author Linbz
 * @data 2022/10/21 15:45
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class JedisMockTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @Order(0)
    public void mvcPostTest() throws Exception {
        MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/jedis/jedisUtilsSetTest")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON);
        MvcResult mvcResult = mockMvc.perform(requestBuilder)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        String response = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
        System.out.println(response);
    }

    @Test
    @Order(1)
    public void mvcGetTest() throws Exception {
        MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/jedis/jedisUtilsGetTest")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON);
        MvcResult mvcResult = mockMvc.perform(requestBuilder)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        String response = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
        System.out.println(response);
    }
}

运行JedisMockTest

image.png

测试通过,控制台打印输出内容:

image.png