基於springboot的restful接口的單元測試示例


一、知識點

代碼中對應的知識點

1.jsonPath

github網址

1)操作符見文檔

2)方法見文檔

3)例子見文檔

2.MockMvc(org.springframework.test.web.servlet.MockMvc)

作用是偽造一個mvc的環境

其方法使用:

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

二、代碼示例

Ⅰ實體部分

1.用戶實體-User

package com.knyel.dto;

public class User {

    private String username;
    private  String password;

    public String getUsername (){
        return username;
    }

    public void setUsername (String username){
        this.username = username;
    }

    public String getPassword (){
        return password;
    }

    public void setPassword (String password){
        this.password = password;
    }

}

Ⅱ 數據傳輸對象(DTO)

1.UserQueryCondition

package com.knyel.dto;

public class UserQueryCondition {
    private String username;
    private int age;
    private int ageTo;
    private String phone;

    public String getUsername (){
        return username;
    }

    public void setUsername (String username){
        this.username = username;
    }

    public int getAge (){
        return age;
    }

    public void setAge (int age){
        this.age = age;
    }

    public int getAgeTo (){
        return ageTo;
    }

    public void setAgeTo (int ageTo){
        this.ageTo = ageTo;
    }

    public String getPhone (){
        return phone;
    }

    public void setPhone (String phone){
        this.phone = phone;
    }

    @Override
    public String toString (){
        return "UserQueryCondition{" + "username='" + username + '\'' + ", age=" + age + ", ageTo=" + ageTo + ", phone='" + phone + '\'' + '}';
    }
}

Ⅲ 控制層controller

1.UserController

package com.knyel.wb.controller;

import com.knyel.dto.User;
import com.knyel.dto.UserQueryCondition;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public List<User> query(UserQueryCondition userQueryCondition, @PageableDefault(page=1,size=10,sort="username,asc") Pageable pageable){
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getSort());
        System.out.println(pageable.getPageSize());
        System.out.println(userQueryCondition.toString());
        List<User> users=new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return  users;
    }
}

Ⅳ 單元測試類

package com.knyel.controller;

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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp (){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void whenQuerySuccess () throws Exception{
        mockMvc.perform(MockMvcRequestBuilders.get("/user")
                .param("username","knyel")
                .param("age","18")
                .param("ageTo","60")
                .param("phone","110")
                .param("size","15")
                .param("page","2")
                .param("sort","age,desc")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value("3"));//查詢的根元素,例如$.length()代表整個傳過來的json的文檔
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM