测试驱动开发TDD

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

以登录请求为例

java 复制代码
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"));
    }
}
相关推荐
摇滚侠2 分钟前
Spring Boot 3零基础教程,Spring Intializer,笔记05
spring boot·笔记·spring
Jabes.yang39 分钟前
Java求职面试实战:从Spring Boot到微服务架构的技术探讨
java·数据库·spring boot·微服务·面试·消息队列·互联网大厂
聪明的笨猪猪42 分钟前
Java Redis “高可用 — 主从复制”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
兮动人1 小时前
Spring Bean耗时分析工具
java·后端·spring·bean耗时分析工具
MESSIR221 小时前
Spring IOC(控制反转)中常用注解
java·spring
摇滚侠1 小时前
Spring Boot 3零基础教程,Demo小结,笔记04
java·spring boot·笔记
笨手笨脚の2 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式·行为型设计模式
spencer_tseng3 小时前
Eclipse 4.7 ADT (Android Development Tools For Eclipse)
android·java·eclipse
聪明的笨猪猪3 小时前
Java Spring “AOP” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
Lucky GGBond4 小时前
Vue + Spring Boot 实现 Excel 导出实例
vue.js·spring boot·excel