使用`MockMvc`来测试带有单个和多个请求参数的`GET`和`POST`接口

简介: 使用`MockMvc`来测试带有单个和多个请求参数的`GET`和`POST`接口

在Spring Boot项目中,使用`MockMvc`可以方便地测试`GET`和`POST`接口。下面是如何使用`MockMvc`来测试带有单个和多个请求参数的`GET`和`POST`接口的示例。

 

1. 准备工作

 

首先,确保你的项目中包含必要的依赖。如果你使用的是Maven,可以在`pom.xml`中添加以下依赖:

 

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
```

 

2. 配置MockMvc

 

在测试类中配置`MockMvc`,可以通过`@WebMvcTest`注解或创建完整的Spring上下文(使用`@SpringBootTest`)来初始化`MockMvc`。

 

```java
@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class) // 替换为你的控制器类
public class YourControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    // 测试方法在这里
}
```

 

3. 测试GET接口

 

3.1 单个请求参数

 

假设我们有一个简单的`GET`接口,接收一个名为`name`的请求参数:

 

```java
@RestController
@RequestMapping("/api")
public class YourController {
 
    @GetMapping("/greet")
    public ResponseEntity<String> greet(@RequestParam String name) {
        return ResponseEntity.ok("Hello, " + name);
    }
}
```

 

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

 

```java
@Test
public void testGreetWithSingleParam() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/api/greet")
            .param("name", "John"))
            .andExpect(status().isOk())
            .andExpect(content().string("Hello, John"));
}
```

 

3.2 多个请求参数

 

假设我们有一个`GET`接口,需要两个请求参数`firstName`和`lastName`:

```java
@GetMapping("/welcome")
public ResponseEntity<String> welcome(@RequestParam String firstName, @RequestParam String lastName) {
    return ResponseEntity.ok("Welcome, " + firstName + " " + lastName);
}
```

 

测试多个请求参数的方法如下:

 

```java
@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"));
}
```

 

4. 测试POST接口

 

4.1 单个请求参数

 

假设我们有一个简单的`POST`接口,接收一个名为`message`的请求体:

 

```java
@PostMapping("/echo")
public ResponseEntity<String> echo(@RequestBody String message) {
    return ResponseEntity.ok(message);
}
```

 

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

 

```java
@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!"));
}
```

 

4.2 多个请求参数

 

假设我们有一个`POST`接口,需要接收一个包含多个字段的JSON对象:

 

```java
@PostMapping("/createUser")
public ResponseEntity<User> createUser(@RequestBody User user) {
    // 假设有一个User类,并且返回创建的用户对象
    return ResponseEntity.ok(user);
}
```

 

假设`User`类如下:

 

```java
public class User {
    private String firstName;
    private String lastName;
    // getters and setters
}
```

 

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

 

```java
@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"));
}
```

 

5. 完整示例

 

以下是完整的测试类示例,包括对`GET`和`POST`接口的测试:

 

```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"));
    }
}
```

 

通过这些示例,我们可以了解如何使用`MockMvc`来测试Spring Boot应用中的`GET`和`POST`接口,处理单个和多个请求参数的场景。

目录
相关文章
|
1天前
|
存储 JSON 测试技术
软件测试之 接口测试 Postman使用(下)
软件测试之 接口测试 Postman使用(下)
11 2
|
1天前
|
测试技术 数据格式
软件测试之 接口测试 Postman使用(上)
软件测试之 接口测试 Postman使用(上)
8 1
|
3天前
|
监控 druid Java
Springboot用JUnit测试接口时报错Failed to determine a suitable driver class configure a DataSource: ‘url‘
Springboot用JUnit测试接口时报错Failed to determine a suitable driver class configure a DataSource: ‘url‘
8 0
|
9天前
|
监控 前端开发 测试技术
postman接口测试工具详解
postman接口测试工具详解
38 7
|
9天前
|
前端开发 测试技术
接口测试:Mock 的价值与意义
Mock测试用于替代复杂或不可用的对象,常见于前后端交互、第三方系统及硬件解耦。它不依赖真实数据,节省工作量和联调时间。核心包括匹配规则(决定修改哪个接口)和模拟响应(设计篡改内容以符合测试用例)。
9 0
|
9天前
|
监控 JavaScript 前端开发
postman接口测试工具详解
postman接口测试工具详解
20 6
|
23天前
|
JSON 测试技术 API
API接口测试指南:确保接口稳定性与可靠性的实践
API接口测试是确保软件产品质量的重要组成部分。通过遵循本指南中的测试步骤和最佳实践,开发者可以有效地验证API的功能、性能和安全性,从而提升软件的整体质量和用户满意度。
|
23天前
|
存储 网络安全 Android开发
接口测试:抓包工具证书配置
Charles 抓包工具配置指南:包括Charles的基础设置,证书安装(Mac和Windows),SSL代理设置,移动端(同一WIFI环境,启用透明HTTP代理)和模拟器的代理配置,以及iOS系统的代理与证书安装步骤。注意Android 6+及iPhone 10+的特殊信任设置。配置完成后,通过Charles进行网络请求监控。
20 0
|
30天前
|
JSON 测试技术 定位技术
软件测试-接口测试
软件测试-接口测试
21 0
|
1月前
|
NoSQL 安全 测试技术
接口测试用例设计的关键步骤与技巧解析
该文介绍了接口测试的设计和实施,包括测试流程、质量目标和用例设计方法。接口测试在需求分析后进行,关注功能、性能、安全等六项质量目标。流程包括网络监听(如TcpDump, WireShark)和代理工具(Charles, BurpSuite, mitmproxy, Fiddler, AnyProxy)。设计用例时,需考虑基本功能流程、输入域测试(如边界值、特殊字符、参数类型、组合参数、幂等性)、线程安全(并发和分布式测试)以及故障注入。接口测试用例要素包括模块、标题、优先级、前置条件、请求方法等。文章强调了保证接口的幂等性和系统健壮性的测试重要性。
57 5