SpringBoot Controller單元測(cè)試

環(huán)境

Windows 10
JDK 1.8
idea 2018.2
SpringBoot 2.1.4

首先創(chuàng)建Controller

package com.zuoyang.springbootjuint.Controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ZuoYangController {
    @GetMapping("/hello")
    public String helloZuoYang(String hi){
        return hi+" 左羊";
    }
}

之后當(dāng)前項(xiàng)目右鍵--》Go To-->Test


image

勾選要進(jìn)行測(cè)試的方法


image

編寫(xiě)測(cè)試類(lèi)

package com.zuoyang.springbootjuint.Controller;

import com.zuoyang.springbootjuint.Application;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;


//SpringBoot1.4版本之前用的是SpringJUnit4ClassRunner.class
@RunWith(SpringRunner.class)
//SpringBoot1.4版本之前用的是@SpringApplicationConfiguration(classes = Application.class)
@SpringBootTest(classes = Application.class)
//測(cè)試環(huán)境使用,用來(lái)表示測(cè)試環(huán)境使用的ApplicationContext將是WebApplicationContext類(lèi)型的
@WebAppConfiguration
public class ZuoYangControllerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;
    @Before
    public void setUp() throws Exception {
        //MockMvcBuilders.webAppContextSetup(WebApplicationContext context):指定WebApplicationContext,將會(huì)從該上下文獲取相應(yīng)的控制器并得到相應(yīng)的MockMvc;
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();//建議使用這種
    }

    @Test
    public void helloZuoYang() throws Exception {
        String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/hello?hi=hi") //請(qǐng)求的url,請(qǐng)求的方法是get
                .contentType(MediaType.APPLICATION_JSON_UTF8) //數(shù)據(jù)的格式
                .accept(MediaType.APPLICATION_JSON_UTF8)
        ).andExpect(MockMvcResultMatchers.status().isOk())  //返回的狀態(tài)是200
                .andDo(MockMvcResultHandlers.print()) //打印出請(qǐng)求和相應(yīng)的內(nèi)容
                .andReturn().getResponse().getContentAsString(); //將相應(yīng)的數(shù)據(jù)轉(zhuǎn)換為字符

        System.out.println(responseString);
    }
}

方法解析:

perform:執(zhí)行一個(gè)RequestBuilder請(qǐng)求,會(huì)自動(dòng)執(zhí)行SpringMVC的流程并映射到相應(yīng)的控制器執(zhí)行處理;
get:聲明發(fā)送一個(gè)get請(qǐng)求的方法。MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根據(jù)uri模板和uri變量值得到一個(gè)GET請(qǐng)求方式的。另外提供了其他的請(qǐng)求的方法,如:post、put、delete等。
param:添加request的參數(shù),如上面發(fā)送請(qǐng)求的時(shí)候帶上了了pcode = root的參數(shù)。假如使用需要發(fā)送json數(shù)據(jù)格式的時(shí)將不能使用這種方式,可見(jiàn)后面被@ResponseBody注解參數(shù)的解決方法
andExpect:添加ResultMatcher驗(yàn)證規(guī)則,驗(yàn)證控制器執(zhí)行完成后結(jié)果是否正確(對(duì)返回的數(shù)據(jù)進(jìn)行的判斷);
andDo:添加ResultHandler結(jié)果處理器,比如調(diào)試時(shí)打印結(jié)果到控制臺(tái)(對(duì)返回的數(shù)據(jù)進(jìn)行的判斷);
andReturn:最后返回相應(yīng)的MvcResult;然后進(jìn)行自定義驗(yàn)證/進(jìn)行下一步的異步處理(對(duì)返回的數(shù)據(jù)進(jìn)行的判斷);

perform:執(zhí)行一個(gè)RequestBuilder請(qǐng)求,會(huì)自動(dòng)執(zhí)行SpringMVC的流程并映射到相應(yīng)的控制器執(zhí)行處理;
get:聲明發(fā)送一個(gè)get請(qǐng)求的方法。MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根據(jù)uri模板和uri變量值得到一個(gè)GET請(qǐng)求方式的。另外提供了其他的請(qǐng)求的方法,如:post、put、delete等。
param:添加request的參數(shù),如上面發(fā)送請(qǐng)求的時(shí)候帶上了了pcode = root的參數(shù)。假如使用需要發(fā)送json數(shù)據(jù)格式的時(shí)將不能使用這種方式,可見(jiàn)后面被@ResponseBody注解參數(shù)的解決方法
andExpect:添加ResultMatcher驗(yàn)證規(guī)則,驗(yàn)證控制器執(zhí)行完成后結(jié)果是否正確(對(duì)返回的數(shù)據(jù)進(jìn)行的判斷);
andDo:添加ResultHandler結(jié)果處理器,比如調(diào)試時(shí)打印結(jié)果到控制臺(tái)(對(duì)返回的數(shù)據(jù)進(jìn)行的判斷);
andReturn:最后返回相應(yīng)的MvcResult;然后進(jìn)行自定義驗(yàn)證/進(jìn)行下一步的異步處理(對(duì)返回的數(shù)據(jù)進(jìn)行的判斷);
contentType :設(shè)置數(shù)據(jù)的格式contentType :設(shè)置數(shù)據(jù)的格式

結(jié)果

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /hello
       Parameters = {hi=[hi]}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json;charset=UTF-8"]
             Body = null
    Session Attrs = {}


Handler:
             Type = com.zuoyang.springbootjuint.Controller.ZuoYangController
           Method = public java.lang.String com.zuoyang.springbootjuint.Controller.ZuoYangController.helloZuoYang(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:"9"]
     Content type = application/json;charset=UTF-8
             Body = hi 左羊
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
hi 左羊

代碼地址
https://github.com/dxf1998/SpringBoot-juint.git
參考鏈接
https://www.cnblogs.com/0201zcr/p/5756642.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容