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

目录
相关文章
|
Cloud Native Go 项目管理
敏捷项目管理解锁:2023年使用YouTrack的全面指南
敏捷项目管理解锁:2023年使用YouTrack的全面指南
4340 0
|
10月前
|
安全 Java API
Spring Boot 4 黑科技: 编译期消灭空指针异常!
NPE被称为“幽灵bug”因Java类型系统无法区分可空/非空类型,导致运行时崩溃。Spring Boot 4引入JSpecify标准:`@NullMarked`设包级非空默认,`@Nullable`显式标注例外,配合NullAway在编译期拦截空指针,让NPE从线上事故变为本地错误。(239字)
558 2
|
10月前
|
XML IDE Java
Spring Boot 4 王炸新特性:Bean 注册新姿势 BeanRegistrar,少写一半代码
Spring Boot 4 正式推出 `BeanRegistrar`——动态注册 Bean 的终极解法!告别冗长 `@Bean` + `@Conditional` 套娃,12 行代码精准按配置注册(如 Email/SMS),启动仅加载所需 Bean,性能提升、可读性飙升。从“声明”迈向“编程式容器”,减负不止 50%。
892 2
|
自然语言处理 安全 Java
【软件测试】教你如何写一份软件测试报告
【软件测试】教你如何写一份软件测试报告
|
存储 缓存 安全
全网最全面介绍唯品会API接口指南
唯品会API助力开发者高效集成商品、订单、用户等功能。本指南详解注册、认证、调用步骤,提供Python示例与安全最佳实践,助你快速上手电商应用开发。(239字)
1137 0
|
XML 缓存 Java
一文讲透程序编排的核心方式:从表达式语言到并行化实践
高德的poi数据来源多种多样,处理流程也多种多样,但因流程相对固定,因此使用了流程化配置简化开发,使用表达式语言保证灵活性。为了加深对平台的理解,并帮助大家对编排有一定的了解,本文会以影响范围的视角去总结当前编排的方案。
638 13
一文讲透程序编排的核心方式:从表达式语言到并行化实践
|
数据采集 数据管理 数据挖掘
数据治理5个最容易混淆的关键词:主数据、元数据、数据质量、数据安全、指标口径,你都搞明白了吗?
企业在数据管理中常面临“听起来都懂,做起来都乱”的困境,尤其对主数据、元数据、数据质量、数据安全与指标口径等关键概念模糊,影响数据治理与业务决策。本文用通俗方式讲清这五大核心概念,帮助企业厘清数据治理基础逻辑,提升数据可用性与业务协同效率,为BI、数据中台等建设打下坚实基础。
|
网络协议 NoSQL Redis
Docker Compose--模板文件
Docker Compose--模板文件
1631 29
|
机器学习/深度学习 搜索推荐 数据可视化
大数据用户画像之基本概念
大数据用户画像利用大数据技术分析用户基本信息、消费行为、兴趣、社交及地理数据,创建详细用户模型,助力企业精准营销。涉及技术包括数据挖掘、大数据处理(Hadoop、Spark)、数据可视化、机器学习和数据库管理。通过用户画像,企业可实现市场定位、个性化推荐、精准广告、产品优化和风险控制。学习该领域需掌握多个技术栈,包括相关算法、工具及业务理解。
2194 4
|
Java 开发者 Spring
springboot @RequiredArgsConstructor @Lazy解决循环依赖的原理
【5月更文挑战第16天】在Spring Boot中,@RequiredArgsConstructor 和 @Lazy 是两个有用的注解,它们分别用于简化构造函数的生成和控制Bean的加载时间。下面详细解析这两个注解的概念、优缺点以及在实际应用中的示例。
2493 1