使用MockMVC测试Spring Boot的REST用例

栏目: Java · 发布时间: 5年前

内容简介:MockMVC类是在这个MockMVC教程中,我们将使用它和Spring boot的WebMvcTest类来执行Maven依赖:

MockMVC类是 Spring MVC 测试框架的一部分,它通过启动一个Servlet容器帮助测试REST控制器。

在这个MockMVC教程中,我们将使用它和Spring boot的WebMvcTest类来执行 Junit 测试用例,该测试用例测试为 Spring boot 2 hateoas 编写的 REST 控制器方法。

Maven依赖:

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

一个JUnit测试类来测试Spring MVC控制器请求和响应,我们可以使用下面给出的配置。

@RunWith(SpringRunner.<b>class</b>)
@WebMvcTest(EmployeeRESTController.<b>class</b>)
<b>public</b> <b>class</b> TestEmployeeRESTController {
 
  @Autowired
  <b>private</b> MockMvc mvc;
 
}
  • SpringRunner 是SpringJUnit4ClassRunner别名。它是JUnit的BlockJUnit4ClassRunner的自定义扩展,它通过TestContextManager和相关的支持类和注释为标准JUnit测试提供Spring TestContext Framework的功能。
  • @WebMvcTest 注释用于Spring MVC测试。它禁用完全自动配置,而只应用与MVC测试相关的配置。
  • WebMvcTest注释将自动配置MockMvc实例。
  • 使用EmployeeRESTController.classas参数,我们要求只初始化一个Web控制器,您需要使用Mock对象提供所需的剩余依赖项。

HTTP GET

假设有一个Rest控制器:

@GetMapping(value = <font>"/employees"</font><font>)
<b>public</b> EmployeeListVO getAllEmployees()
{
    </font><font><i>//code</i></font><font>
}
 
@GetMapping(value = </font><font>"/employees/{id}"</font><font>)
<b>public</b> ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable(</font><font>"id"</font><font>) <b>int</b> id)
{
    </font><font><i>//code</i></font><font>
}
</font>

下面给出了相应的方法测试:

@Autowired
<b>private</b> MockMvc mvc;
 
@Test
<b>public</b> <b>void</b> getAllEmployeesAPI() throws Exception
{
  mvc.perform( MockMvcRequestBuilders
      .get(<font>"/employees"</font><font>)
      .accept(MediaType.APPLICATION_JSON))
      .andDo(print())
      .andExpect(status().isOk())
      .andExpect(MockMvcResultMatchers.jsonPath(</font><font>"$.employees"</font><font>).exists())
      .andExpect(MockMvcResultMatchers.jsonPath(</font><font>"$.employees<li>.employeeId"</font><font>).isNotEmpty());
}
 
@Test
<b>public</b> <b>void</b> getEmployeeByIdAPI() throws Exception
{
  mvc.perform( MockMvcRequestBuilders
      .get(</font><font>"/employees/{id}"</font><font>, 1)
      .accept(MediaType.APPLICATION_JSON))
      .andDo(print())
      .andExpect(status().isOk())
      .andExpect(MockMvcResultMatchers.jsonPath(</font><font>"$.employeeId"</font><font>).value(1));
}
</font>

HTTP POST

案例:

@PostMapping(value = <font>"/employees"</font><font>)
<b>public</b> ResponseEntity<EmployeeVO> addEmployee (@Valid @RequestBody EmployeeVO employee)
{
    </font><font><i>//code</i></font><font>
    <b>return</b> <b>new</b> ResponseEntity<EmployeeVO>(employee, HttpStatus.CREATED);
}
</font>

对于post json请求的相应spring springmvc测试如下:

@Autowired
<b>private</b> MockMvc mvc;
 
@Test
<b>public</b> <b>void</b> createEmployeeAPI() throws Exception
{
  mvc.perform( MockMvcRequestBuilders
      .post(<font>"/employees"</font><font>)
      .content(asJsonString(<b>new</b> EmployeeVO(<b>null</b>, </font><font>"firstName4"</font><font>, </font><font>"lastName4"</font><font>, </font><font>"email4@mail.com"</font><font>)))
      .contentType(MediaType.APPLICATION_JSON)
      .accept(MediaType.APPLICATION_JSON))
      .andExpect(status().isCreated())
      .andExpect(MockMvcResultMatchers.jsonPath(</font><font>"$.employeeId"</font><font>).exists());
}
 
<b>public</b> <b>static</b> String asJsonString(<b>final</b> Object obj) {
    <b>try</b> {
        <b>return</b> <b>new</b> ObjectMapper().writeValueAsString(obj);
    } <b>catch</b> (Exception e) {
        <b>throw</b> <b>new</b> RuntimeException(e);
    }
}
</font>

HTTP PUT

HTTP API在控制器中定义为:

@PutMapping(value = <font>"/employees/{id}"</font><font>)
<b>public</b> ResponseEntity<EmployeeVO> updateEmployee (@PathVariable(</font><font>"id"</font><font>) <b>int</b> id, @Valid @RequestBody EmployeeVO employee)
{
    </font><font><i>//code</i></font><font>
    <b>return</b> <b>new</b> ResponseEntity<EmployeeVO>(emp, HttpStatus.OK);
}
</font>

相应的方法测试是

@Test
<b>public</b> <b>void</b> updateEmployeeAPI() throws Exception
{
  mvc.perform( MockMvcRequestBuilders
      .put(<font>"/employees/{id}"</font><font>, 2)
      .content(asJsonString(<b>new</b> EmployeeVO(2, </font><font>"firstName2"</font><font>, </font><font>"lastName2"</font><font>, </font><font>"email2@mail.com"</font><font>)))
      .contentType(MediaType.APPLICATION_JSON)
      .accept(MediaType.APPLICATION_JSON))
      .andExpect(status().isOk())
      .andExpect(MockMvcResultMatchers.jsonPath(</font><font>"$.firstName"</font><font>).value(</font><font>"firstName2"</font><font>))
      .andExpect(MockMvcResultMatchers.jsonPath(</font><font>"$.lastName"</font><font>).value(</font><font>"lastName2"</font><font>))
      .andExpect(MockMvcResultMatchers.jsonPath(</font><font>"$.email"</font><font>).value(</font><font>"email2@mail.com"</font><font>));
}
</font>

HTTP DELETE:

@DeleteMapping(value = <font>"/employees/{id}"</font><font>)
<b>public</b> ResponseEntity<HttpStatus> removeEmployee (@PathVariable(</font><font>"id"</font><font>) <b>int</b> id)
{
    </font><font><i>//code</i></font><font>
    <b>return</b> <b>new</b> ResponseEntity<HttpStatus>(HttpStatus.ACCEPTED);
}
</font>

相应的方法测试是:

@Test
<b>public</b> <b>void</b> deleteEmployeeAPI() throws Exception
{
  mvc.perform( MockMvcRequestBuilders.delete(<font>"/employees/{id}"</font><font>, 1) )
        .andExpect(status().isAccepted());
}
</font>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

用户至上:用户研究方法与实践(原书第2版)

用户至上:用户研究方法与实践(原书第2版)

凯茜·巴克斯特 / 王兰、杨雪、苏寅 / 机械工业出版社 / 2017-5-1 / 99

《UI/UE系列丛书 用户至上:用户研究方法与实践(原书第2版)》是用户研究方法指南,谷歌用户体验研究员十几年工作经验结晶,从理论到实战,包含完整的实操案例,是设计以人为中心产品的实用手册。 《UI/UE系列丛书 用户至上:用户研究方法与实践(原书第2版)》包含五个部分共15章。入门篇包括第1~5章:介绍用户体验入门,如何理解目标用户,道德与法律问题,如何搭建研究设施,如何选择用户体验研究方......一起来看看 《用户至上:用户研究方法与实践(原书第2版)》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换