springboot2.7编写controller测试类
时间: 2023-08-03 09:58:46 浏览: 72
当编写 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` 注解来指