SpringBoot2种单元测试方法解析

 更新时间:2019年10月29日 10:28:10   作者:天宇轩-王  
这篇文章主要介绍了SpringBoot2种单元测试方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一 普通测试类

当有一个测试方法的时候,直接运行。

要在方法前后做事情,可以用before或者after。

假如有多个方法运行,则可以选择类进行运行。

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
  @Test
  public void testOne(){
    System.out.println("test hello 1");
    TestCase.assertEquals(1, 1);   
  } 
  @Test
  public void testTwo(){
    System.out.println("test hello 2");
    TestCase.assertEquals(1, 1);    
  }  
  @Before
  public void testBefore(){
    System.out.println("before");
  }  
  @After
  public void testAfter(){
    System.out.println("after");
  }​
}

测试结果:

2019-10-28 21:17:25.466 INFO 18872 --- [      main] com.example.demo.TestApplicationTests  : Started TestApplicationTests in 1.131 seconds (JVM running for 5.525)
before
test hello 1
after
before
test hello 2
after

二 MockMvc

1 perform方法其实只是为了构建一个请求,并且返回ResultActions实例,该实例则是可以获取到请求的返回内容。

2 MockMvcRequestBuilders该抽象类则是可以构建多种请求方式,如:Post、Get、Put、Delete等常用的请求方式,其中参数则是我们需要请求的本项目的相对路径,/则是项目请求的根路径。

3 param方法用于在发送请求时携带参数,当然除了该方法还有很多其他的方法,大家可以根据实际请求情况选择调用。

4 andReturn方法则是在发送请求后需要获取放回时调用,该方法返回MvcResult对象,该对象可以获取到返回的视图名称、返回的Response状态、获取拦截请求的拦截器集合等。

5 我们在这里就是使用到了第4步内的MvcResult对象实例获取的MockHttpServletResponse对象从而才得到的Status状态码。

6 同样也是使用MvcResult实例获取的MockHttpServletResponse对象从而得到的请求返回的字符串内容。【可以查看rest返回的json数据】

7 使用Junit内部验证类Assert判断返回的状态码是否正常为200

8 判断返回的字符串是否与我们预计的一样。

要测试 Spring MVC 控制器是否正常工作,您可以使用@WebMvcTest annotation。 @WebMvcTest将 auto-configure Spring MVC 基础架构并将扫描的 beans 限制为@Controller,@ControllerAdvice,@JsonComponent,Filter,WebMvcConfigurer和HandlerMethodArgumentResolver。使用此 annotation 时,不会扫描常规@Component beans。

@WebMvcTest通常仅限于一个控制器,并与@MockBean结合使用。

@WebMvcTest也 auto-configures MockMvc。 Mock MVC 提供了一种快速测试 MVC 控制器的强大方法,无需启动完整的 HTTP 服务器。

您也可以通过@AutoConfigureMockMvc注释非@WebMvcTest(e.g. SpringBootTest)auto-configure MockMvc。

import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.mock.mockito.*;
​
import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
​
@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public class MyControllerTests {
​
  @Autowired
  private MockMvc mvc;
​
  @MockBean
  private UserVehicleService userVehicleService;
​
  @Test
  public void testExample() throws Exception {
    given(this.userVehicleService.getVehicleDetails("sboot"))
        .willReturn(new VehicleDetails("Honda", "Civic"));
    this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
        .andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
  }
}

如果需要配置 auto-configuration 的元素(对于应用 servlet 过滤器的 example),可以使用@AutoConfigureMockMvc annotation 中的属性。

如果您使用 HtmlUnit 或 Selenium,auto-configuration 还将提供WebClient bean and/or a WebDriver bean。这是一个使用 HtmlUnit 的 example:

import com.gargoylesoftware.htmlunit.*;
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.mock.mockito.*;
​
import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*;
​
@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public class MyHtmlUnitTests {
​
  @Autowired
  private WebClient webClient;
​
  @MockBean
  private UserVehicleService userVehicleService;
​
  @Test
  public void testExample() throws Exception {
    given(this.userVehicleService.getVehicleDetails("sboot"))
        .willReturn(new VehicleDetails("Honda", "Civic"));
    HtmlPage page = this.webClient.getPage("/sboot/vehicle.html");
    assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic");
  }
​
}

默认情况下 Spring Boot 会将WebDriver beans 放在一个特殊的“范围”中,以确保在每次测试后退出驱动程序,并注入新实例。如果您不想要此行为,可以将@Scope("singleton")添加到WebDriver @Bean定义中。

测试

@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
//@SpringBootTest(classes={TestApplicationTests.class}) //启动整个springboot工程
//@AutoConfigureMockMvc 
@WebMvcTest(TestController.class)
public class MockMvcTestDemo {  
  @Autowired
  private MockMvc mockMvc;  
  @Test
  public void apiTest() throws Exception {  
    MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/test/hello") ).
        andExpect( MockMvcResultMatchers.status().isOk() ).andReturn();
    int status = mvcResult.getResponse().getStatus();
    System.out.println(status);
    
     String responseString = mockMvc.perform( MockMvcRequestBuilders.get("/test/hello") ).
        andExpect( MockMvcResultMatchers.status().isOk() ).andDo(print())     //打印出请求和相应的内容
     .andReturn().getResponse().getContentAsString();
     System.out.println(responseString);   
  } 
}
@RestController
public class TestController {
  
  @RequestMapping("/test/hello")
  public String test() {
    return "hello";
  }
​}
​

结果:

2019-10-28 22:02:18.022 INFO 5736 --- [      main] com.example.demo.MockMvcTestDemo     : Started MockMvcTestDemo in 2.272 seconds (JVM running for 3.352)
​
MockHttpServletRequest:
   HTTP Method = GET
   Request URI = /test/hello
    Parameters = {}
     Headers = []
       Body = <no character encoding set>
  Session Attrs = {}
​
Handler:
       Type = com.example.demo.web.TestController
      Method = public java.lang.String com.example.demo.web.TestController.test()
​
Async:
  Async started = false
   Async result = null
​
Resolved Exception:
       Type = null
​
ModelAndView:
    View name = null
       View = null
      Model = null
​
FlashMap:
    Attributes = null
​
MockHttpServletResponse:
      Status = 200
  Error message = null
     Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"5"]
   Content type = text/plain;charset=UTF-8
       Body = hello
  Forwarded URL = null
  Redirected URL = null
     Cookies = []
hello

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

相关文章

  • SpringBoot LocalDateTime格式转换方案详解(前端入参)

    SpringBoot LocalDateTime格式转换方案详解(前端入参)

    这篇文章主要介绍了SpringBoot LocalDateTime格式转换(前端入参),本文用示例介绍SpringBoot全局格式配置,将前端传过来的时间自动转化为LocalDateTime,需要的朋友可以参考下
    2023-04-04
  • 浅析Java 并发编程中的synchronized

    浅析Java 并发编程中的synchronized

    这篇文章主要介绍了Java 并发编程中的synchronized的相关资料,帮助大家更好的理解和学习Java并发编程,感兴趣的朋友可以了解下
    2020-12-12
  • Swagger2配置Security授权认证全过程

    Swagger2配置Security授权认证全过程

    这篇文章主要介绍了Swagger2配置Security授权认证全过程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Struts2的配置 struts.xml Action详解

    Struts2的配置 struts.xml Action详解

    这篇文章主要介绍了Struts2的配置 struts.xml Action详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • SpringBoot中@Value获取值和@ConfigurationProperties获取值用法及比较

    SpringBoot中@Value获取值和@ConfigurationProperties获取值用法及比较

    在Spring Boot中,@Value注解是一个非常有用的特性,它允许我们将外部的配置注入到我们的Bean中,@ConfigurationProperties用于将配置文件中的属性绑定到 Java Bean 上,本文介绍了@Value获取值和@ConfigurationProperties获取值用法及比较,需要的朋友可以参考下
    2024-08-08
  • 浅谈Spring Boot 微服务项目的推荐部署方式

    浅谈Spring Boot 微服务项目的推荐部署方式

    这篇文章主要介绍了浅谈Spring Boot 微服务项目的推荐部署方式,具有一定参考价值,需要的朋友可以了解下。
    2017-09-09
  • 线上Java程序占用CPU过高解决方案

    线上Java程序占用CPU过高解决方案

    这篇文章主要介绍了线上Java程序占用CPU过高解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Java排序的那些事之sort方法的使用详解

    Java排序的那些事之sort方法的使用详解

    sort方法用于对数组的元素进行排序。排序顺序可以是字母或数字,并按升序或降序。默认排序顺序为按字母升序,当数字是按字母顺序排列时"40"将排在"5"前面。使用数字排序,你必须通过一个函数作为参数来调用。这些说起来可能很难理解,你可以通过本篇文章进一步了解它
    2021-09-09
  • 深入理解Java动态代理与静态代理

    深入理解Java动态代理与静态代理

    这篇文章主要介绍了深入理解Java动态代理与静态代理,静态代理,代理类和被代理的类实现了同样的接口,代理类同时持有被代理类的引用,动态代理的根据实现方式的不同可以分为JDK动态代理和CGlib动态代理
    2022-06-06
  • java中BigDecimal用法详解

    java中BigDecimal用法详解

    本文详细讲解了java中BigDecimal的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12

最新评论