使用MockMVC测试Spring Boot的REST用例

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

内容简介: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>

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

查看所有标签

猜你喜欢:

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

Java Concurrency in Practice

Java Concurrency in Practice

Brian Goetz、Tim Peierls、Joshua Bloch、Joseph Bowbeer、David Holmes、Doug Lea / Addison-Wesley Professional / 2006-5-19 / USD 59.99

This book covers: Basic concepts of concurrency and thread safety Techniques for building and composing thread-safe classes Using the concurrency building blocks in java.util.concurrent Pe......一起来看看 《Java Concurrency in Practice》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具