欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot2種單元測(cè)試方法解析

 更新時(shí)間:2019年10月29日 10:28:10   作者:天宇軒-王  
這篇文章主要介紹了SpringBoot2種單元測(cè)試方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

一 普通測(cè)試類(lèi)

當(dāng)有一個(gè)測(cè)試方法的時(shí)候,直接運(yùn)行。

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

假如有多個(gè)方法運(yùn)行,則可以選擇類(lèi)進(jìn)行運(yùn)行。

@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");
  }​
}

測(cè)試結(jié)果:

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方法其實(shí)只是為了構(gòu)建一個(gè)請(qǐng)求,并且返回ResultActions實(shí)例,該實(shí)例則是可以獲取到請(qǐng)求的返回內(nèi)容。

2 MockMvcRequestBuilders該抽象類(lèi)則是可以構(gòu)建多種請(qǐng)求方式,如:Post、Get、Put、Delete等常用的請(qǐng)求方式,其中參數(shù)則是我們需要請(qǐng)求的本項(xiàng)目的相對(duì)路徑,/則是項(xiàng)目請(qǐng)求的根路徑。

3 param方法用于在發(fā)送請(qǐng)求時(shí)攜帶參數(shù),當(dāng)然除了該方法還有很多其他的方法,大家可以根據(jù)實(shí)際請(qǐng)求情況選擇調(diào)用。

4 andReturn方法則是在發(fā)送請(qǐng)求后需要獲取放回時(shí)調(diào)用,該方法返回MvcResult對(duì)象,該對(duì)象可以獲取到返回的視圖名稱(chēng)、返回的Response狀態(tài)、獲取攔截請(qǐng)求的攔截器集合等。

5 我們?cè)谶@里就是使用到了第4步內(nèi)的MvcResult對(duì)象實(shí)例獲取的MockHttpServletResponse對(duì)象從而才得到的Status狀態(tài)碼。

6 同樣也是使用MvcResult實(shí)例獲取的MockHttpServletResponse對(duì)象從而得到的請(qǐng)求返回的字符串內(nèi)容?!究梢圆榭磖est返回的json數(shù)據(jù)】

7 使用Junit內(nèi)部驗(yàn)證類(lèi)Assert判斷返回的狀態(tài)碼是否正常為200

8 判斷返回的字符串是否與我們預(yù)計(jì)的一樣。

要測(cè)試 Spring MVC 控制器是否正常工作,您可以使用@WebMvcTest annotation。 @WebMvcTest將 auto-configure Spring MVC 基礎(chǔ)架構(gòu)并將掃描的 beans 限制為@Controller,@ControllerAdvice,@JsonComponent,F(xiàn)ilter,WebMvcConfigurer和HandlerMethodArgumentResolver。使用此 annotation 時(shí),不會(huì)掃描常規(guī)@Component beans。

@WebMvcTest通常僅限于一個(gè)控制器,并與@MockBean結(jié)合使用。

@WebMvcTest也 auto-configures MockMvc。 Mock MVC 提供了一種快速測(cè)試 MVC 控制器的強(qiáng)大方法,無(wú)需啟動(dòng)完整的 HTTP 服務(wù)器。

您也可以通過(guò)@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 的元素(對(duì)于應(yīng)用 servlet 過(guò)濾器的 example),可以使用@AutoConfigureMockMvc annotation 中的屬性。

如果您使用 HtmlUnit 或 Selenium,auto-configuration 還將提供WebClient bean and/or a WebDriver bean。這是一個(gè)使用 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");
  }
​
}

默認(rèn)情況下 Spring Boot 會(huì)將WebDriver beans 放在一個(gè)特殊的“范圍”中,以確保在每次測(cè)試后退出驅(qū)動(dòng)程序,并注入新實(shí)例。如果您不想要此行為,可以將@Scope("singleton")添加到WebDriver @Bean定義中。

測(cè)試

@RunWith(SpringRunner.class) //底層用junit SpringJUnit4ClassRunner
//@SpringBootTest(classes={TestApplicationTests.class}) //啟動(dòng)整個(gè)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())     //打印出請(qǐng)求和相應(yīng)的內(nèi)容
     .andReturn().getResponse().getContentAsString();
     System.out.println(responseString);   
  } 
}
@RestController
public class TestController {
  
  @RequestMapping("/test/hello")
  public String test() {
    return "hello";
  }
​}
​

結(jié)果:

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Springboot啟動(dòng)執(zhí)行特定代碼的方式匯總

    Springboot啟動(dòng)執(zhí)行特定代碼的方式匯總

    這篇文章主要介紹了Springboot啟動(dòng)執(zhí)行特定代碼的幾種方式,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-12-12
  • SpringBoot啟動(dòng)后的初始化數(shù)據(jù)加載原理解析與實(shí)戰(zhàn)

    SpringBoot啟動(dòng)后的初始化數(shù)據(jù)加載原理解析與實(shí)戰(zhàn)

    本文主要圍繞?Spring?Boot?啟動(dòng)后的初始化數(shù)據(jù)加載展開(kāi),介紹了初始化任務(wù)的基本需求,包括全局配置加載、數(shù)據(jù)庫(kù)表初始化等,闡述了多種初始化加載方式,分析了它們的優(yōu)缺點(diǎn),需要的朋友可以參考下
    2024-11-11
  • 解決mapper自動(dòng)裝配識(shí)別不了,Could not autowire.No beans of‘UserMapper‘type found

    解決mapper自動(dòng)裝配識(shí)別不了,Could not autowire.No beans&

    文章介紹了在使用MyBatisX插件和MybatisPlus自動(dòng)生成代碼后,如何解決Spring Boot項(xiàng)目中自動(dòng)注入`UserMapper`時(shí)報(bào)錯(cuò)的問(wèn)題,主要方法包括在主配置類(lèi)或啟動(dòng)類(lèi)上添加`@MapperScan`注解,指定Mapper文件夾所在的包路徑,以及在Mapper類(lèi)上添加`@Repository`注解
    2024-11-11
  • 如何解決java.lang.NoClassDefFoundError:Could not initialize class java.awt.Color問(wèn)題

    如何解決java.lang.NoClassDefFoundError:Could not initi

    文章講述了在Java服務(wù)器中處理圖形元素時(shí)遇到的常見(jiàn)問(wèn)題,即需要運(yùn)行X-server,通過(guò)在Tomcat/bin/catalina.sh中增加JAVA_OPTS環(huán)境變量并設(shè)置-Djava.awt.headless=true,可以解決這個(gè)問(wèn)題,使服務(wù)器能夠在沒(méi)有圖形界面的情況下運(yùn)行
    2024-11-11
  • IntelliJ?IDEA?2022.2最新版本激活教程(親測(cè)可用版)永久激活工具分享

    IntelliJ?IDEA?2022.2最新版本激活教程(親測(cè)可用版)永久激活工具分享

    Jetbrains官方發(fā)布了?IntelliJ?IDEA2022.2?正式版,每次大的版本更新,都會(huì)有較大的調(diào)整和優(yōu)化,除本次更新全面擁抱?Java?17?外,還有對(duì)IDE?UI界面,安全性,便捷性等都做了調(diào)整和優(yōu)化完善,用戶(hù)體驗(yàn)提升不少,相信后面會(huì)有不少小伙伴跟著更新
    2022-08-08
  • Java中AIO、BIO、NIO應(yīng)用場(chǎng)景及區(qū)別

    Java中AIO、BIO、NIO應(yīng)用場(chǎng)景及區(qū)別

    本文主要介紹了Java中AIO、BIO、NIO應(yīng)用場(chǎng)景及區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • Java Hutool(糊涂)工具類(lèi)索引詳解

    Java Hutool(糊涂)工具類(lèi)索引詳解

    這篇文章主要介紹了Java Hutool(糊涂)工具類(lèi)索引,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • mybatis 為什么千萬(wàn)不要使用 where 1=1

    mybatis 為什么千萬(wàn)不要使用 where 1=1

    這篇文章主要介紹了mybatis 為什么千萬(wàn)不要使用 where 1=1,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-05-05
  • SpringBoot2.x的依賴(lài)管理配置

    SpringBoot2.x的依賴(lài)管理配置

    這篇文章主要介紹了SpringBoot2.x的依賴(lài)管理配置,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • redis發(fā)布訂閱Java代碼實(shí)現(xiàn)過(guò)程解析

    redis發(fā)布訂閱Java代碼實(shí)現(xiàn)過(guò)程解析

    這篇文章主要介紹了redis發(fā)布訂閱Java代碼實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09

最新評(píng)論