使用`MockMvc`额外的补充和高级用法

简介: 使用`MockMvc`额外的补充和高级用法

使用`MockMvc`额外的补充和高级用法

 

1. 处理路径变量的GET请求

 

假设你的控制器有一个带路径变量的`GET`接口:

 

```java
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
    // 假设通过ID获取用户信息
    User user = new User(id, "John", "Doe");
    return ResponseEntity.ok(user);
}
```

 

测试这个接口的方法如下:

 

```java
@Test
public void testGetUserById() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/api/users/{id}", 1L))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.id").value(1))
            .andExpect(jsonPath("$.firstName").value("John"))
            .andExpect(jsonPath("$.lastName").value("Doe"));
}
```

 

2. 处理带Header的请求

 

假设你的控制器需要处理带特定`Header`的请求:

 

```java
@PostMapping("/secured")
public ResponseEntity<String> securedEndpoint(@RequestHeader("Authorization") String authorizationHeader) {
    if ("Bearer valid_token".equals(authorizationHeader)) {
        return ResponseEntity.ok("Access granted");
    } else {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Access denied");
    }
}
```

 

测试这个接口的方法如下:

 

```java
@Test
public void testSecuredEndpointWithValidToken() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.post("/api/secured")
            .header("Authorization", "Bearer valid_token"))
            .andExpect(status().isOk())
            .andExpect(content().string("Access granted"));
}
 
@Test
public void testSecuredEndpointWithInvalidToken() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.post("/api/secured")
            .header("Authorization", "Bearer invalid_token"))
            .andExpect(status().isUnauthorized())
            .andExpect(content().string("Access denied"));
}
```

 

3. 处理文件上传的POST请求

 

假设你的控制器需要处理文件上传:

 

```java
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
    // 假设处理文件上传逻辑
    return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
}
```

 

测试文件上传的方法如下:

 

```java
@Test
public void testHandleFileUpload() throws Exception {
    MockMultipartFile file = new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes());
 
    mockMvc.perform(MockMvcRequestBuilders.multipart("/api/upload").file(file))
            .andExpect(status().isOk())
            .andExpect(content().string("File uploaded successfully: test.txt"));
}
```

 

4. 验证请求体中的JSON字段

 

假设你有一个需要验证请求体中JSON字段的`POST`接口:

 

```java
@PostMapping("/createOrder")
public ResponseEntity<Order> createOrder(@RequestBody Order order) {
    // 假设有一个Order类,并且返回创建订单对象
    return ResponseEntity.ok(order);
}
```

 

假设`Order`类如下:

 

```java
public class Order {
    private Long id;
    private String product;
    private Integer quantity;
    // getters and setters
}
```

 

测试这个接口的方法如下:

 

```java
@Test
public void testCreateOrder() throws Exception {
    String orderJson = "{\"id\":1, \"product\":\"Laptop\", \"quantity\":2}";
 
    mockMvc.perform(MockMvcRequestBuilders.post("/api/createOrder")
            .content(orderJson)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.id").value(1))
            .andExpect(jsonPath("$.product").value("Laptop"))
            .andExpect(jsonPath("$.quantity").value(2));
}
```

 

5. 测试异常处理

 

假设你的控制器有全局异常处理:

 

```java
@RestControllerAdvice
public class GlobalExceptionHandler {
 
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }
}
```

 

在控制器中抛出`ResourceNotFoundException`:

 

```java
@GetMapping("/resource/{id}")
public ResponseEntity<String> getResource(@PathVariable Long id) {
    throw new ResourceNotFoundException("Resource not found with id " + id);
}
```

 

测试异常处理的方法如下:

 

```java
@Test
public void testResourceNotFoundException() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/api/resource/{id}", 1L))
            .andExpect(status().isNotFound())
            .andExpect(content().string("Resource not found with id 1"));
}
```

 

6. 完整的测试类示例

 

以下是包含所有上述测试的完整测试类示例:

 

```java
@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class)
public class YourControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    public void testGreetWithSingleParam() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/greet")
                .param("name", "John"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, John"));
    }
 
    @Test
    public void testWelcomeWithMultipleParams() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/welcome")
                .param("firstName", "John")
                .param("lastName", "Doe"))
                .andExpect(status().isOk())
                .andExpect(content().string("Welcome, John Doe"));
    }
 
    @Test
    public void testEchoWithSingleParam() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/echo")
                .content("Hello, World!")
                .contentType(MediaType.TEXT_PLAIN))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, World!"));
    }
 
    @Test
    public void testCreateUserWithMultipleParams() throws Exception {
        String userJson = "{\"firstName\":\"John\", \"lastName\":\"Doe\"}";
 
        mockMvc.perform(MockMvcRequestBuilders.post("/api/createUser")
                .content(userJson)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.firstName").value("John"))
                .andExpect(jsonPath("$.lastName").value("Doe"));
    }
 
    @Test
    public void testGetUserById() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/users/{id}", 1L))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id").value(1))
                .andExpect(jsonPath("$.firstName").value("John"))
                .andExpect(jsonPath("$.lastName").value("Doe"));
    }
 
    @Test
    public void testSecuredEndpointWithValidToken() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/secured")
                .header("Authorization", "Bearer valid_token"))
                .andExpect(status().isOk())
                .andExpect(content().string("Access granted"));
    }
 
    @Test
    public void testSecuredEndpointWithInvalidToken() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/secured")
                .header("Authorization", "Bearer invalid_token"))
                .andExpect(status().isUnauthorized())
                .andExpect(content().string("Access denied"));
    }
 
    @Test
    public void testHandleFileUpload() throws Exception {
        MockMultipartFile file = new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes());
 
        mockMvc.perform(MockMvcRequestBuilders.multipart("/api/upload").file(file))
                .andExpect(status().isOk())
                .andExpect(content().string("File uploaded successfully: test.txt"));
    }
 
    @Test
    public void testCreateOrder() throws Exception {
        String orderJson = "{\"id\":1, \"product\":\"Laptop\", \"quantity\":2}";
 
        mockMvc.perform(MockMvcRequestBuilders.post("/api/createOrder")
                .content(orderJson)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id").value(1))
                .andExpect(jsonPath("$.product").value("Laptop"))
                .andExpect(jsonPath("$.quantity").value(2));
    }
 
    @Test
    public void testResourceNotFoundException() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/resource/{id}", 1L))
                .andExpect(status().isNotFound())
                .andExpect(content().string("Resource not found with id 1"));
    }
}
```

 

通过这些示例,我们可以更好地理解如何使用`MockMvc`来测试Spring Boot应用中的各种情况,包括路径变量、请求头、文件上传、JSON请求体验证以及异常处理。

目录
相关文章
|
缓存 算法 网络协议
面向5G的阿里自研标准化协议库XQUIC
XQUIC是阿里巴巴淘系架构团队自研的IETF QUIC标准化协议库实现,在手机淘宝上进行了广泛的应用,并在多个不同类型的业务场景下取得明显的效果提升,为手机淘宝APP的用户带来丝般顺滑的网络体验: 在RPC请求场景,网络耗时降低15% 在直播高峰期场景,卡顿率降低30%、秒开率提升2% 在短视频场景,卡顿率降低20%
4627 1
面向5G的阿里自研标准化协议库XQUIC
24Echarts - 折线图(Line Style and Item Style)
24Echarts - 折线图(Line Style and Item Style)
165 0
|
移动开发 供应链 Java
企业级智能制造MES系统源码,技术架构:springboot + vue-element-plus-admin
企业级智能制造MES系统源码,技术架构:springboot + vue-element-plus-admin。 企业级云MES全套源码,支持app、小程序、H5、台后管理。 生产调度:MES系统可以根据生产订单和资源状况,自动计算生产计划和调度,从而优化生产线的运作。
453 0
企业级智能制造MES系统源码,技术架构:springboot + vue-element-plus-admin
|
11月前
|
JavaScript 前端开发
使用 WebGL 创建 3D 动画
【10月更文挑战第3天】使用 WebGL 创建 3D 动画
|
8月前
|
敏捷开发 人工智能 JavaScript
Figma-Low-Code:快速将Figma设计转换为Vue.js应用,支持低代码渲染、数据绑定
Figma-Low-Code 是一个开源项目,能够直接将 Figma 设计转换为 Vue.js 应用程序,减少设计师与开发者之间的交接时间,支持低代码渲染和数据绑定。
519 3
Figma-Low-Code:快速将Figma设计转换为Vue.js应用,支持低代码渲染、数据绑定
|
SQL Oracle 关系型数据库
MySQL数据库,从入门到精通:第一篇——MySQL概念详解(二)
MySQL数据库,从入门到精通:第一篇——MySQL概念详解(二)
671 0
|
人工智能 自然语言处理 搜索推荐
10分钟构建AI客服:阿里云技术解决方案评测
在数字化转型的浪潮中,企业对客户服务的即时性和个性化需求愈发迫切。阿里云推出的“10分钟构建AI客服并应用到网站、钉钉、微信中”的技术解决方案,为企业提供了一个快速、低成本的AI客服部署方案。本文将从部署流程、用户体验、成本效益等方面对这一方案进行深入评测。
1040 3
|
10月前
|
监控 负载均衡 网络协议
OSPF在大型网络中的应用:高效路由与可扩展性
OSPF在大型网络中的应用:高效路由与可扩展性
716 1
|
人工智能 分布式计算 大数据
AI Native平台,跨越AI应用从创新到生产的鸿沟
2024年是AI应用的元年,以大模型为中心的 AI Native 应用大爆发正在从理想变成现实。云计算带来的应用创新潮,经历了虚拟机时代和云原生时代,正在全面拥抱以大模型为核心的 AI Native 阶段,推动大数据与AI的工作流前所未有地紧密结合。领先大模型、高效的AI计算平台和统一的大数据平台是 AI Native 应用广泛落地背后不可获缺的要素。 9月20日,2024云栖大会上,阿里云副总裁、阿里云计算平台事业部负责人汪军华宣布大数据AI平台全面升级,为 AI Native 应用大爆发提供坚实的平台支撑。
uniapp 打包成 apk(原生APP-云打包)免费
uniapp 打包成 apk(原生APP-云打包)免费
1352 1