spring-boot-starter-test

頂風少年發表於2022-02-22

排除Junit4

springboot2.2.x以下的版本,只包含junit4.x的版本

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>

引入test

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

 

引入2.2.x以上的springboot則包含Junit4.x和Junit5.x兩個版本

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/>
    </parent>

使用springboot-test時檢視使用的版本中是否同時包含兩個版本,如果都包含則可以排除Junit4

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

MockMvc測試介面

編寫一個get介面,呼叫了service層,無需啟動伺服器

    @Autowired
    private TestService testService;
 
    @GetMapping(value = "/test1")
    public String test1() {
        testService.test1();
        return "success";
    }
public void test1(){}//service

測試get請求 @SpringBootTest 會根據路徑尋找 @SpringBootApplication 或 @SpringBootConfiguration所以請保持test目錄結構與main目錄結構相同。否則要

使用@SpringBootTest(classes="Application.class")主動標記啟動類。

@SpringBootTest
@AutoConfigureMockMvc
public class TestController {
    @Autowired
    private MockMvc mvc;
    @Test
    public void test1() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/test1")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string("success"));
    }
}

@MockBean模擬bean

編寫一個get介面,呼叫了service層,在service返回字串service1

    @Autowired
    private TestService testService;
    @GetMapping(value = "test")
    public String test() {
        return testService.service1();
    }
public String service1(){
        return "service1";
    }

通過@MockBean注入TestService。使用BDDMockito.given()給service1()重新搞一個返回值。這個請求返回的是mockvalue而不是service1。事實上將service類上

的@Service註解去掉,即沒有這個業務bean這個測試類也會成功執行。

 @MockBean
    private TestService remoteService;
@Test
    public void test2() throws Exception {
        given(this.remoteService.service1()).willReturn("mockvalue");
        String contentAsString = mockMvc.perform(MockMvcRequestBuilders.get("/test"))
                .andReturn().getResponse().getContentAsString();
        System.out.println("!!!!!!!!!!!!!!!!"+contentAsString);
    }

@JsonTest測試JSON

JacksonTester的功能和JSONObject類似。

spring-boot-starter-test
public class VehicleDetails {
    private String make;
    private String model;
    public String getMake() {
        return make;
    }
    public void setMake(String make) {
        this.make = make;
    }
    public String getModel() {
        return model;
    }
    public void setModel(String model) {
        this.model = model;
    }
}
View Code
@JsonTest
public class TestController2 {
    @Autowired
    private JacksonTester<VehicleDetails> json;

    @Test
    void testDeserialize() throws Exception {
        String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
        VehicleDetails vehicleDetails = this.json.parseObject(content);
        System.out.println(vehicleDetails.getMake()+""+vehicleDetails.getModel());
    }

addReturn()

設定MediaType,設定Head.addReturn()返回請求結果.

@SpringBootTest
@AutoConfigureMockMvc
public class TestController {
    @Autowired
    MockMvc mvc;
    @Test
    public void test2()throws Exception{
        Person p = new Person();
        p.setName("張三");
        p.setAge(11);
        MockHttpServletResponse response = mvc.perform(MockMvcRequestBuilders.post("/test2").contentType(MediaType.APPLICATION_JSON)
                .content(JSONObject.toJSONString(p)).header("test-head", "head-value")).andReturn().getResponse();
        String contentAsString = response.getContentAsString(Charset.forName("utf-8"));
        System.out.println(response.getHeader("test2-head"));
        System.out.println(contentAsString);
    }
}
@PostMapping(value = "test2")
    public Person test2(@RequestBody Person person, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("!!!!!!!!!!!!!"+person);
        System.out.println("!!!!!!!!!!!!!"+request.getHeader("test-head"));
        response.addHeader("test2-head","headvalue");
        return testService.testService(person);
    }

 

 

andDo()

好像只能列印請求

@SpringBootTest
@AutoConfigureMockMvc
public class TestController {
    @Autowired
    MockMvc mvc;
    @Test
    public void test3() throws Exception {
        Person p = new Person();
        p.setName("張三");
        p.setAge(11);
        ResultActions actions = mvc.perform(MockMvcRequestBuilders.post("/test2")
                .contentType(MediaType.APPLICATION_JSON).content(JSONObject.toJSONString(p)));
        actions.andReturn().getResponse().setCharacterEncoding("utf-8");
        actions.andDo(MockMvcResultHandlers.print());
    }
}
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /test2
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"26"]
             Body = {"age":11,"name":"張三"}
    Session Attrs = {}

Handler:
             Type = com.datang.qqboark.controller.DemoController
           Method = com.datang.qqboark.controller.DemoController#test2(Person, HttpServletRequest, HttpServletResponse)

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 = [test2-head:"headvalue", Content-Type:"application/json;charset=utf-8"]
     Content type = application/json
             Body = {"name":"張三","age":11}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

andExpect()

增加斷言MockMvcResultMatchers斷言HTTP狀態,斷言head,斷言返回值.

@SpringBootTest
@AutoConfigureMockMvc
public class TestController {
    @Autowired
    MockMvc mvc;
    @Test
    public void test4() throws Exception {
        Person p = new Person();
        p.setName("張三");
        p.setAge(11);
        ResultActions actions = mvc.perform(MockMvcRequestBuilders.post("/test2")
                .contentType(MediaType.APPLICATION_JSON).content(JSONObject.toJSONString(p)));
        actions.andReturn().getResponse().setCharacterEncoding("utf-8");
        actions.andExpect(MockMvcResultMatchers.status().isOk());
        actions.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
        actions.andExpect(MockMvcResultMatchers.header().string("test2-head","headvalue"));
        actions.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON));
        actions.andExpect(MockMvcResultMatchers.content().json(JSONObject.toJSONString(p)));
    }
}