java单元测试:springmvc接口测试MockMvc
·
MockMvc 是 Spring 测试框架中的一个重要工具,用于在不启动真实服务器的情况下测试 Spring MVC 控制器。它提供了一种方式来模拟 HTTP 请求,并验证控制器的行为和响应。以下是 MockMvc 的详细介绍:
MockMvc 的基本功能
- 模拟 HTTP 请求:模拟 GET、POST、PUT、DELETE 等 HTTP 请求。
- 验证响应:验证响应状态码、响应内容、响应头等。
- 设置请求参数:设置请求路径参数、查询参数、请求体等。
- 配置 Mock 依赖:通过 MockBean 注解可以轻松地替换控制器的依赖。
配置 MockMvc
在使用 MockMvc 进行测试之前,需要进行一些配置:
- 引入依赖:确保在项目的
pom.xml文件中引入了 Spring Boot Starter Test 依赖。 - 设置测试类:使用
@ExtendWith(SpringExtension.class)和@WebMvcTest注解来配置测试环境。 - 注入 MockMvc 实例:使用
@Autowired注入 MockMvc 实例。
MockMvc 示例代码
以下是一个详细的示例代码,展示如何使用 MockMvc 测试一个简单的 Spring MVC 控制器:
1. 控制器类
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
@GetMapping("/{id}")
public String getUserById(@PathVariable("id") Long id) {
return "User ID: " + id;
}
@GetMapping("/search")
public String searchUsers(@RequestParam("name") String name) {
return "Search results for: " + name;
}
}
2. 测试类
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnHelloWorld() throws Exception {
mockMvc.perform(get("/api/users/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
@Test
public void shouldReturnUserById() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(content().string("User ID: 1"));
}
@Test
public void shouldReturnSearchResults() throws Exception {
mockMvc.perform(get("/api/users/search")
.param("name", "John"))
.andExpect(status().isOk())
.andExpect(content().string("Search results for: John"));
}
}
MockMvc 的主要方法
- perform(RequestBuilder requestBuilder): 执行请求。
- andExpect(ResultMatcher matcher): 验证结果。
- andDo(ResultHandler handler): 添加结果处理器,用于调试(如打印响应内容)。
- param(String name, String… values): 设置请求参数。
- header(String name, Object value): 设置请求头。
更多推荐
所有评论(0)