SpringBoot 如何使用 MockMvc 进行 Web 集成测试

SpringBoot 如何使用 MockMvc 进行 Web 集成测试

介绍

SpringBoot 是一个流行的 Java Web 开发框架,它提供了一些强大的工具和库,使得开发 Web 应用程序变得更加容易。其中之一是 MockMvc,它提供了一种测试 SpringBoot Web 应用程序的方式,可以模拟 HTTP 请求和响应的行为。

在本文中,我们将介绍 SpringBoot 中的 MockMvc,演示如何使用它进行 Web 集成测试。

MockMvc

MockMvc 是 SpringFramework 中的一个测试工具,用于模拟 HTTP 请求和响应的行为。MockMvc 可以模拟发送 GET、POST、PUT、DELETE 等 HTTP 请求,并验证响应的状态码、内容类型和响应体等。

在 SpringBoot 中,我们可以使用 MockMvc 进行 Web 集成测试。下面是一个简单的例子:

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGetUser() throws Exception {
        mockMvc.perform(get("/users/{id}", 1))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.id").value(1))
                .andExpect(jsonPath("$.name").value("John Doe"))
                .andExpect(jsonPath("$.age").value(25));
    }
}

在上面的代码中,我们使用 @SpringBootTest 和 @AutoConfigureMockMvc 注释 SpringBoot 应用程序和 MockMvc。然后,我们使用 @Autowired 注释注入 MockMvc 对象。最后,我们使用 perform 方法模拟发送 GET 请求,并使用 andExpect 方法验证响应的状态码、内容类型和响应体等。

如何使用 MockMvc 进行 Web 集成测试

要使用 MockMvc 进行 Web 集成测试,请按照以下步骤操作:

第 1 步:添加依赖

在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-testartifactId>
    <scope>testscope>
dependency>

在上面的代码中,我们添加了一个 spring-boot-starter-test 依赖,它包含了许多测试相关的依赖。

第 2 步:启用 MockMvc

在测试类中添加 @SpringBootTest 和 @AutoConfigureMockMvc 注释启用 MockMvc。

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
    ...
}

在上面的代码中,我们使用 @SpringBootTest 注释启用 SpringBoot 应用程序,并使用 @AutoConfigureMockMvc 注释启用 MockMvc。

第 3 步:注入 MockMvc 对象

在测试类中使用 @Autowired 注释注入 MockMvc 对象。

@Autowired
private MockMvc mockMvc;

在上面的代码中,我们使用 @Autowired 注释注入 MockMvc 对象。

第 4 步:模拟 HTTP 请求

使用 MockMvc 对象的 perform 方法模拟 HTTP 请求。

mockMvc.perform(get("/users/{id}", 1))

在上面的代码中,我们使用 get 方法模拟发送 GET 请求。在路径中使用占位符 {id},可以在后面的参数列表中指定实际的 id 值。

第 5 步:验证响应状态码

使用 andExpect 方法验证响应的状态码。

.andExpect(status().isOk())

在上面的代码中,我们使用 status 方法获取响应的状态码,并使用 isOk 方法验证状态码是否为 200。

第 6 步:验证响应内容类型

使用 andExpect 方法验证响应的内容类型。

.andExpect(content().contentType(MediaType.APPLICATION_JSON))

在上面的代码中,我们使用 content 方法获取响应的内容类型,并使用 contentType 方法验证内容类型是否为 JSON。

第 7 步:验证响应体

使用 andExpect 方法验证响应的内容。

.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$.age").value(25));

在上面的代码中,我们使用 jsonPath 方法获取响应体中的 JSON 属性,并使用 value 方法验证属性的值是否正确。

示例

以下是一个完整的示例:

UserController.java

@RestController
@RequestMapping("/users")
public class UserController {

    private List<User> users = new ArrayList<>();

    @GetMapping("/{id}")
    public User getUser(@PathVariable int id) {
        return users.stream()
                .filter(user -> user.getId() == id)
                .findFirst()
                .orElse(null);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        int nextId = users.size() + 1;
        user.setId(nextId);
        users.add(user);
        return user;
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable int id, @RequestBody User user) {
        User existingUser = users.stream()
                .filter(u -> u.getId() == id)
                .findFirst()
                .orElse(null);
        if (existingUser != null) {
            existingUser.setName(user.getName());
            existingUser.setAge(user.getAge());
        }
        return existingUser;
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable int id) {
        users.removeIf(user -> user.getId() == id);
    }

}

UserControllerTest.java

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGetUser() throws Exception {
        mockMvc.perform(get("/users/{id}", 1))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.id").value(1))
                .andExpect(jsonPath("$.name").value("John Doe"))
                .andExpect(jsonPath("$.age").value(25));
    }

    @Test
    public void testCreateUser() throws Exception {
        User user = new User();
        user.setName("Jane Doe");
        user.setAge(30);

        mockMvc.perform(post("/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(user)))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.id").isNumber())
                .andExpect(jsonPath("$.name").value("Jane Doe"))
                .andExpect(jsonPath("$.age").value(30));
    }

    @Test
    public void testUpdateUser() throws Exception {
        User user = new User();
        user.setName("Jane Doe");
        user.setAge(30);

        mockMvc.perform(put("/users/{id}", 1)
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(user)))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.id").value(1))
                .andExpect(jsonPath("$.name").value("Jane Doe"))
                .andExpect(jsonPath("$.age").value(30));
    }

    @Test
    public void testDeleteUser() throws Exception {
        mockMvc.perform(delete("/users/{id}", 1))
                .andExpect(status().isOk());

        mockMvc.perform(get("/users/{id}", 1))
                .andExpect(status().isOk())
                .andExpect(content().string(""));
    }

    private String asJsonString(Object obj) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

在上面的示例中,我们创建了一个 UserController 类,并实现了 GET、POST、PUT 和 DELETE 方法。然后,我们创建了一个 UserControllerTest 类,并使用 MockMvc 对象模拟发送 HTTP 请求,并验证响应的状态码、内容类型和响应体等。我们还定义了一个 asJsonString 方法,用于将对象转换为 JSON 字符串。

结论

使用 MockMvc 进行 Web 集成测试是一种方便快捷的方式,可以有效地测试 SpringBoot Web 应用程序的功能。在本文中,我们介绍了 MockMvc 的基本概念和用法,并演示了如何使用 MockMvc 进行 Web 集成测试。如果你正在开发 SpringBoot Web 应用程序,建议你使用 MockMvc 进行集成测试,以确保你的应用程序能够正常工作。

你可能感兴趣的:(Java,教程,spring,boot,前端,集成测试)