怎么在SpringBoot2中實現(xiàn)單元測試

今天就跟大家聊聊有關怎么在SpringBoot2中實現(xiàn)單元測試,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

在叢臺等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供成都做網(wǎng)站、成都網(wǎng)站制作 網(wǎng)站設計制作按需網(wǎng)站設計,公司網(wǎng)站建設,企業(yè)網(wǎng)站建設,成都品牌網(wǎng)站建設,全網(wǎng)整合營銷推廣,外貿(mào)網(wǎng)站制作,叢臺網(wǎng)站建設費用合理。

一 普通測試類

當有一個測試方法的時候,直接運行。

要在方法前后做事情,可以用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");
  }
}

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

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

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

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

5 我們在這里就是使用到了第4步內(nèi)的MvcResult對象實例獲取的MockHttpServletResponse對象從而才得到的Status狀態(tài)碼。

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

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

8 判斷返回的字符串是否與我們預計的一樣。

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

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

@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 放在一個特殊的“范圍”中,以確保在每次測試后退出驅(qū)動程序,并注入新實例。如果您不想要此行為,可以將@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())     //打印出請求和相應的內(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

springboot是什么

springboot一種全新的編程規(guī)范,其設計目的是用來簡化新Spring應用的初始搭建以及開發(fā)過程,SpringBoot也是一個服務于框架的框架,服務范圍是簡化配置文件。

看完上述內(nèi)容,你們對怎么在SpringBoot2中實現(xiàn)單元測試有進一步的了解嗎?如果還想了解更多知識或者相關內(nèi)容,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

當前標題:怎么在SpringBoot2中實現(xiàn)單元測試
文章地址:http://muchs.cn/article20/pdphco.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供Google做網(wǎng)站、網(wǎng)頁設計公司、云服務器標簽優(yōu)化、網(wǎng)站維護

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運營