1. 程式人生 > >SpringBoot(十五):MockMVC-web單元測試

SpringBoot(十五):MockMVC-web單元測試

版權宣告

單純的廣告

個人部落格:https://aodeng.cc
微信公眾號:低調小熊貓
QQ群:756796932

簡介

開發一個優秀的系統,單元測試也是必不可少的,Spring Boot 對單元測試也做了一些支援,MockMVC就是之一,可以模擬web端的post,get請求,測試也能得到詳細的過程

使用方法

新增依賴

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

編寫測試程式碼

@SpringBootTest
public class Springboot13StarterTestApplicationTests {

    private MockMvc mockMvc;

    //初始化資源
    @Before
    public void setMockMvc() throws Exception{
        mockMvc= MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void test() throws Exception{
        mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=低調小熊貓")
                .accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print());
    }
    @Test
    public void test2() throws Exception{
        mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=低調小熊貓")
                .accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("低調小熊貓")));

    }
    @Test
    public void contextLoads() {
        System.out.println("低調小熊貓");
    }

}

程式碼作用
accept(MediaType.APPLICATION_JSON_UTF8)) 設定編碼格式
andDo(print()) //會將請求和相應的過程都打印出來
Matchers.containsString("str"),判斷返回的結果集中是否包含“str”這個字串

執行測試

我們執行第一個test

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /hello
       Parameters = {name=[低調小熊貓]}
          Headers = {Accept=[application/json;charset=UTF-8]}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.hope.controller.HelloController
           Method = public java.lang.String com.hope.controller.HelloController.hello(java.lang.String)

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=[application/json;charset=UTF-8], Content-Length=[21]}
     Content type = application/json;charset=UTF-8
             Body = 你好低調小熊貓
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

當看到“Body = 你好低調小熊貓”,表示成功了,還能看到整個請求詳細資訊

第二個test,會列印我們請求的結果

第三個測試,就是普通的測試了

以上程式碼只是spring-boot-starter-test 元件的一部分功能,還有很多好玩的一起學吧

原始碼

https://github.com/java-aodeng/hope

這只是我個人的學習筆記,非教程