测试驱动开发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("[email protected]", "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("[email protected]"))
                .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("urfread"));
    }
}

你可能感兴趣的:(前后端&数据库交互通信,spring,tdd,java,spring,spring,boot,java-ee)