controller测试类

本文详细介绍了如何进行Spring MVC的Controller单元测试,包括测试环境搭建、请求模拟、响应验证等关键步骤,帮助开发者确保控制器代码的正确性和稳定性。
摘要由CSDN通过智能技术生成
package com.xiaolyuh;
 
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
import java.util.HashMap;
import java.util.Map;
 
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
 
import net.minidev.json.JSONObject;
 
@RunWith(SpringRunner.cl
当编写 Spring Boot 2.7 版本的 Controller 测试时,你可以使用 Spring MVC 的测试框架来进行测试。以下是一个简单的示例: 首先,确保你的项目中已经添加了相关的测试依赖,例如 `spring-boot-starter-test`。 然后,创建一个测试,可以使用 JUnit 或者其他测试框架来进行测试。示例代码如下: ```java 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 UserControllerTest { @Autowired private MockMvc mockMvc; @Test public void testGetUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/users/{id}", 1) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("John Doe")); } @Test public void testCreateUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/users") .contentType(MediaType.APPLICATION_JSON) .content("{\"name\": \"Jane Smith\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").exists()); } // 更多测试方法... } ``` 在上述示例中,我们使用了 `@SpringBootTest` 注解来指
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值