Spring Boot MockMvc 测试 Web RESTful Api

简述:

之前就有看到大佬的 blog 中写过关于Mockmvc的使用方法,但是却没有系统的学一下,由于实在不想每次测试http请求都启动一下服务器,最终还是没忍住。


enjoy coding!

包含了四种请求方式的学习:

  • GET
  • POST
  • PUT
  • DELETE

环境准备(myself):

  • Jdk 8
  • Springboot 2.0.5
  • Lombok 1.18.2

添加依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<!-- lombok -->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.2</version>
   <scope>provided</scope>
</dependency>

实体类

/**
 * @author innerpeacez
 * @since 2019/1/7
 */
@Data
@AllArgsConstructor
public class Employee {

    private String firstName;
    private String lastName;
    private String email;
}

Controller 控制器

定义好 CURD 的四种 http 请求方式。

RESTful Api 是这个样子的:

methodurlDescription
GET/employee/{id}获取一个雇员
GET/employee获取所有雇员
DELETE/employee删除一个雇员
POST/employee增加一个雇员
PUT/employee修改一个雇员信息
/**
 * @author innerpeacez
 * @since 2019/1/8
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    /**
     * 保存雇员信息的容器
     */
    private static Map<Integer, Employee> employeeMap = new LinkedHashMap<>();

    /**
     * 静态方法初始化一些雇员信息,方便测试
     */
    static {
        Employee employee1 = new Employee("zhang", "san", "zhangsan@xx.com");
        Employee employee2 = new Employee("li", "si", "lisi@xx.com");
        employeeMap.put(1, employee1);
        employeeMap.put(2, employee2);
    }

    /**
     * 获取一个雇员
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Employee getEmployee(@PathVariable Integer id) {
        return employeeMap.get(id);
    }

    /**
     * 获取所有雇员
     * @return
     */
    @GetMapping
    public Map<Integer, Employee> getEmployees() {
        return employeeMap;
    }

    /**
     * 增加一个雇员
     * @param employee
     * @return 增加的雇员信息
     */
    @PostMapping
    public Employee addEmployee(Employee employee) {
        return employeeMap.put(employeeMap.size() + 1, employee);
    }

    /**
     * 删除一个雇员
     * @param id
     * @return 删除的雇员信息
     */
    @DeleteMapping
    public Employee deleteEmployee(@RequestParam Integer id) {
        return employeeMap.remove(id);
    }

    /**
     * 修改一个雇员的信息
     * @param id
     * @param employee
     * @return 修改操作之前的雇员信息
     */
    @PutMapping
    public Employee updateEmployee(Integer id, Employee employee) {
        return employeeMap.replace(id, employee);
    }
}

MockMvc测试类

@RunWith注解:SpringRunner.class使用 Junit 整合 Spring

@WebMvcTest注解:寻找测试的 Controller 中的 Mappling

MockMvc: 注入 MockMvc 模拟 Http 请求

MockMvcRequestBuilders抽象类

类中分装了Http请求的Method,如:

  • post()
  • get()
  • put()
  • delete()

使用这些方法时可以设置请求头Header,入参方式,出参方式,验证返回条件,获取返回值等操作。

具体的操作通过下面三种方式实现:

  • andExpect() // 匹配返回信息的预期状态
  • andDo() // 处理返回值,有print(),log()等操作
  • andReturn() // 获取返回值,MvcResult。

测试Http请求代码

/**
 * @author innerpeacez
 * @since 2019/1/9
 */
@RunWith(SpringRunner.class)
@WebMvcTest(EmployeeController.class) // 需要测试的 Controller
public class EmployeeControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testPost() throws Exception {
        MvcResult mvcResult = mockMvc.perform(post("/employee") //设置请求方式为 post 及 url
                .accept(MediaType.APPLICATION_JSON) // 设置入参方式为json
                .param("lastName", "wu")
                .param("email", "wangwu@xx.com")
                .contentType(MediaType.APPLICATION_JSON)) // 设置出参方式json
                .andExpect(status().isOk()) // 设置请求的状态码为 200,可以添加一些期望的响应的结果判断
                .andDo(print()) // print 方法打印出请求体,响应体
                .andReturn(); // 获取返回值MvcResult
        System.out.println(mvcResult.getResponse().getContentAsString());

        testGetAll();
    }

    @Test
    public void testGetOne() throws Exception {
        mockMvc.perform(get("/employee/1")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print()) //
                .andReturn(); // 获取返回值
    }

    @Test
    public void testGetAll() throws Exception {
        MvcResult mvcResult = mockMvc.perform(get("/employee")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print()).andReturn();
        System.out.println(mvcResult.getResponse().getContentAsString());
    }

    @Test
    public void testPut() throws Exception {
        MvcResult mvcResult = mockMvc.perform(put("/employee")
                .accept(MediaType.APPLICATION_JSON)
                .param("id", "1")
                .param("firstName", "张")
                .param("lastName", "三")
                .param("email", "zhangsan@xx.com")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();

        System.out.println("修改之前的值:" + mvcResult.getResponse().getContentAsString());
        testGetOne();
    }


    @Test
    public void testDelete() throws Exception {
        MvcResult mvcResult = mockMvc.perform(delete("/employee/1")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();

        System.out.println("删除之前的值:" + mvcResult.getResponse().getContentAsString());
        testGetOne();
    }
}

总结

本文简单的学习了一下 MockMvc 怎么使用,包含了主要的 CRUD 请求的方式,再也不用启动服务器来测试 http 请求啦。

GitHub 源码地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 项目的单元测试通常使用 JUnit 和 Spring Test 模块。下面是一个简单的 Spring Boot 单元测试示例代码: ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.SqlConfig; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringJUnitConfig @SpringBootTest @AutoConfigureMockMvc @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @DataJpaTest public class UserControllerTest { @Autowired private MockMvc mockMvc; @Test @Sql(scripts = "/data.sql", config = @SqlConfig(encoding = "UTF-8")) public void getUserByIdTest() throws Exception { MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/users/1")) .andExpect(status().isOk()) .andReturn(); String content = result.getResponse().getContentAsString(); assertEquals("{\"id\":1,\"name\":\"John\",\"age\":30}", content); } } ``` 上面的示例代码演示了如何编写一个测试 `UserController` 的单元测试。在 Spring Boot 中,我们通常使用 `@SpringBootTest` 注解来启动整个应用程序上下文,使用 `@AutoConfigureMockMvc` 注解来注入 MockMvc 对象,以便测试控制器的 RESTful API。我们还可以使用 `@DataJpaTest` 注解和 `@AutoConfigureTestDatabase` 注解来配置测试数据库,以便测试持久化操作。在这个例子中,我们还使用了 `@Sql` 注解来执行 SQL 脚本,以便在测试前准备测试数据。 总的来说,Spring Boot 的单元测试相比传统的单元测试更加复杂,但是也更加强大和灵活。我们可以根据具体的测试需求来选择合适的测试工具和策略。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值