Junit單元測試之MockMvc


在測試restful風格的接口時,springmvc為我們提供了MockMVC架構,使用起來也很方便。

下面寫個筆記,便於以后使用時參考備用。

一 場景

1 . 提供一個restful風格的接口

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import qinfeng.zheng.mockmvcdemo.dto.User;

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

@RestController
public class UserController {
    
    @GetMapping("/users")
    public List<User> getUserList() {
        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        return users;
    }
}

 

@Data
public class User {
    private String username;
    private String password;
}

 

2. MockMVC測試代碼

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 AppTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

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

    @Test
    public void getUserList() throws Exception {
        // perform : 執行請求 ;  MockMvcRequestBuilders.get("/url") : 構造一個get請求
        mockMvc.perform(MockMvcRequestBuilders.get("/users")// 請求type : json
                .contentType(MediaType.APPLICATION_JSON))
                // 期望的結果狀態 200
                .andExpect(MockMvcResultMatchers.status().isOk())
                // 期望的返回結果集合有2個元素 , $: 返回結果
                .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));
    }
}

 

3. 運行測試代碼 

 

 

 

 

 

 

 

二 場景2

1. 提供一個restful接口

 @GetMapping("/getUser")
 public User getUser(String username) {
      User user = new User();
      user.setUsername(username);
      user.setPassword("123");
      return user;
 }

 

2. 測試代碼 

  @Test
    public void getUserByUsername() throws Exception {
        // perform : 執行請求 ;  MockMvcRequestBuilders.get("/url") : 構造一個get請求
        mockMvc.perform(MockMvcRequestBuilders.get("/getUser")
                .param("username","admin")
                // 請求type : json
                .contentType(MediaType.APPLICATION_JSON))
                // 期望的結果狀態 200
                .andExpect(MockMvcResultMatchers.status().isOk())
                // 期望的返回結果集合有2個元素 , $: 返回結果
                .andExpect(MockMvcResultMatchers.jsonPath("$.password").value("123"));
    }

 

三 場景3

1. 提供一個restful風格的接口

 @GetMapping("/getUser3")
    public User getUserList(User user) {
        System.out.println(ReflectionToStringBuilder.toString(user,ToStringStyle.MULTI_LINE_STYLE));
        user.setUsername(user.getUsername()+",UK");
        user.setPassword(user.getPassword()+",US");
        return user;
    }

 

2. MockMVC測試代碼

 @Test
    public void test3() throws Exception {
        // perform : 執行請求 ;  MockMvcRequestBuilders.get("/url") : 構造一個get請求
        mockMvc.perform(MockMvcRequestBuilders.get("/getUser3")
                //springmvc會將username,password封裝成一個User對象
                .param("username","admin")
                .param("password","123")
                // 請求type : json
                .contentType(MediaType.APPLICATION_JSON))
                // 期望的結果狀態 200
                .andExpect(MockMvcResultMatchers.status().isOk())
                // 期望的返回結果集合有2個元素 , $: 返回結果
                .andExpect(MockMvcResultMatchers.jsonPath("$.password").value("123,US"));
    }

 

四 場景4

1. 接口代碼

  /**
     * {id:\d+} 正則表達式表明id只能是數字
     * @param id
     * @return
     */
    @GetMapping("/user/{id:\\d+}")
    public User getUserInfo(@PathVariable("id") String id) {
        User user = new User();
        return user;
    }

 

2. 測試代碼

    @Test
    public void test4() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/user/a")
                .contentType(MediaType.APPLICATION_JSON))
                // 期待返回的狀態碼是4XX
                .andExpect(MockMvcResultMatchers.status().is4xxClientError());
    }

 

五 post請求

1. 接口代碼

  @PostMapping("/user")
    public User createUser(@RequestBody User user) {
        System.out.println(user);
        user.setAge(100);
        return user;
    }

 

2. 測試代碼 

 @Test
    public void testCreateUser() throws Exception {
        String jsonUser = "{\"username\":\"admin\",\"password\":\"123\"}";
        mockMvc.perform(MockMvcRequestBuilders.post("/user")
                .contentType(MediaType.APPLICATION_JSON)
                .content(jsonUser))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.age").value("100"));
    }

3. 測試結果

 


免責聲明!

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



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