• 测试驱动开发TDD


    如何在后端测试代码,测试一个其前端的请求,能否正常处理
    以登录请求为例

    package com.example.demo.login;
    
    import com.example.demo.login.pojo.User;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.jupiter.api.Test;
    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.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
    
    @SpringBootTest
    @AutoConfigureMockMvc
    public class LoginTest {
    
        @Autowired
        private MockMvc mockMvc;
    
        @Autowired
        private ObjectMapper objectMapper;
    
        final private String urlTemplate = "/login";
    
        /**
         * 测试POST请求是否正常处理。
         * 发送一个JSON格式的POST请求到"/login"路径,并验证返回内容。
         */
        @Test
        public void testLogin() throws Exception {
            // 创建User对象
            User user = new User("test@qq.com", "123456");
    
            // 使用Jackson库的ObjectMapper将对象转换为JSON字符串
            String jsonRequest = objectMapper.writeValueAsString(user);
    
            // 发送一个 POST 请求到 "/login" 路径
            mockMvc.perform(MockMvcRequestBuilders.post(urlTemplate)
                            // 设置请求的 Content-Type 为 JSON 格式
                            .contentType(MediaType.APPLICATION_JSON)
                            // 设置请求体为 JSON 格式的字符串,模拟客户端发送的 JSON 数据
                            .content(jsonRequest))
                    // 断言返回的内容包含用户信息
                    .andExpect(MockMvcResultMatchers.jsonPath("$.email").value("test@qq.com"))
                    .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("urfread"));
        }
    }
    
    
  • 相关阅读:
    判断日期区间或季节等
    【MySQL】存储引擎
    智慧化工园区管理平台综合解决方案
    Redis_RDB
    RAID技术复习笔记
    Unity之ShaderGraph如何实现光边溶解
    亿级流量系统架构之如何设计高容错分布式计算系统
    pandas教程:Essential Functionality 索引 过滤 映射 排序
    金仓数据库KingbaseES备份与恢复工具手册(还原与恢复)
    学术 | [LaTex]超详细Texlive2022+Tex Studio下载安装配置
  • 原文地址:https://blog.csdn.net/m0_69886881/article/details/139784890