欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > 测试驱动开发TDD

测试驱动开发TDD

2024/10/24 9:18:49 来源:https://blog.csdn.net/m0_69886881/article/details/139784890  浏览:    关键词:测试驱动开发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 {@Autowiredprivate MockMvc mockMvc;@Autowiredprivate ObjectMapper objectMapper;final private String urlTemplate = "/login";/*** 测试POST请求是否正常处理。* 发送一个JSON格式的POST请求到"/login"路径,并验证返回内容。*/@Testpublic 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"));}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com