使用`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请求体验证以及异常处理。

目录
相关文章
|
2月前
|
缓存 监控 程序员
Python中的装饰器是一种特殊类型的声明,它允许程序员在不修改原有函数或类代码的基础上,通过在函数定义前添加额外的逻辑来增强或修改其行为。
【6月更文挑战第30天】Python装饰器是无侵入性地增强函数行为的工具,它们是接收函数并返回新函数的可调用对象。通过`@decorator`语法,可以在不修改原函数代码的情况下,添加如日志、性能监控等功能。装饰器促进代码复用、模块化,并保持源代码整洁。例如,`timer_decorator`能测量函数运行时间,展示其灵活性。
27 0
|
2月前
|
前端开发 JavaScript
详尽分享组件的封装方法【比较高级方法】★★★★★★★
详尽分享组件的封装方法【比较高级方法】★★★★★★★
|
3月前
|
Oracle Java 关系型数据库
Generator【SpringBoot集成】代码生成+knife4j接口文档(2种模板设置、逻辑删除、字段填充 含代码粘贴可用)保姆级教程(注意事项+建表SQL+代码生成类封装+测试类)
Generator【SpringBoot集成】代码生成+knife4j接口文档(2种模板设置、逻辑删除、字段填充 含代码粘贴可用)保姆级教程(注意事项+建表SQL+代码生成类封装+测试类)
67 0
|
XML NoSQL Java
干掉 CRUD!这个API开发神器效率爆炸,无需定义MVC类!!
magic-api 能够只通过 UI 界面就能完成简单常用的接口开发,能够支持市面上多数的关系性数据库,甚至还支持非关系性数据库 MongoDB。 通过 magic-api 提供的 UI 界面完成接口的开发,自动映射为 HTTP 接口,无需定义 Controller、Service、Dao、Mapper、XML、VO 等 Java 对象和相关文件! 该项目已经有上千家公司使用,上万名开发者使用,并有上百名程序员提交建议,20+ 贡献者,是非常值得信赖的项目!
|
存储 XML 缓存
Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(一)(下)
Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(一)
68 0
|
缓存 Java Spring
Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(二)(下)
Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(二)(下)
72 0
|
存储 XML 前端开发
Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(二)(上)
Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(二)
51 0
|
XML 存储 Java
Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(一)(上)
Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(一)
82 0
|
小程序 前端开发 Java
java如何利用JWT和注解,自定义参数的方式优雅实现小程序用户Id管理
在我们的开发项目中,经常需要用到用户ID,比如在小程序商城系统中,我们将商品加入购物车,这时前端就需要发送请求,携带上用户的ID。基本上很多种请求操作都需要携带用户ID,如果每个请求都需要我们往data中添加id的话,那样需要写很多重复代码,并且代码也不美观;所以我们可以利用JWT跟注解的方式来实现;
181 0
|
JSON jenkins 持续交付
python接口自动化(十六)--参数关联接口后传(详解)
大家对前边的自动化新建任务之后,接着对这个新建任务操作了解之后,希望带小伙伴进一步巩固胜利的果实,夯实基础。因此再在沙场实例演练一下博客园的相关接口。我们用自动化发随笔之后,要想接着对这篇随笔操作,不用说就需 要用参数关联了,发随笔之后会有一个随笔的 id,获取到这个 id,继续操作传这个随笔 id 就可以了(博客园的登录机制已经变了,不能用账号和密码登录了,这里用 cookie 登录)
190 1
python接口自动化(十六)--参数关联接口后传(详解)