spring boot單元測試之八:用mockmvc模擬header參數(spring boot 2.4.4)


一,演示項目的相關信息

1,項目地址:

https://github.com/liuhongdi/headertest

2,功能說明:演示了單元測試時傳遞header參數

3,項目結構:如圖:

 

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

說明:作者:劉宏締 郵箱: 371125307@qq.com

二,java代碼說明

1,controller/HomeController.java

@Controller
@RequestMapping("/home")
public class HomeController {

    //顯示home頁面
    @GetMapping("/home")
    public String login() {
        return "home/home";
    }

    //接收header參數
    @GetMapping("/send")
    @ResponseBody
    public String send(HttpServletRequest httpServletRequest) {
        String h1 = httpServletRequest.getHeader("h1");
        String h2 = httpServletRequest.getHeader("h2");
        String h3 = httpServletRequest.getHeader("h3");
        return "res:"+h1+"_"+h2+"_"+h3;
    }
}

 

2,home/home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>測試發送header</title>
</head>
<body>
<div>
    <input type="button" id="btnSave" onclick="go_send()"  value="發送header信息" />
</div>
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.js"></script>
<script>
      //發送驗證碼:
      function go_send() {
          $.ajax({
              cache: true,
              type: "GET",
              url: "/home/send",
              dataType: "text",
              async: true,
              beforeSend: function(request) {
                  request.setRequestHeader("h1","h1aa");
                  request.setRequestHeader("h2","h2bb");
                  request.setRequestHeader("h3","h3cc");
              },
              error: function (request) {
                  console.log("Connection error");
              },
              success: function (data) {
                  //save token
                  console.log("data:");
                  console.log(data);
                  alert(data);
              }
          });
      }
</script>
</body>
</html>

 

3,controller/HomeControllerTest.java

@AutoConfigureMockMvc
@SpringBootTest
class HomeControllerTest {

    @Autowired
    private HomeController homeController;

    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("測試讀取header值")
    void send() throws Exception {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("h1","h1aa");
        httpHeaders.add("h2","h2bb");
        httpHeaders.add("h3","h3cc");

        MvcResult mvcResult = mockMvc.perform(get("/home/send")
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        System.out.println("返回:"+content);
        assertThat(content, equalTo("res:h1aa_h2bb_h3cc"));
    }

    @Test
    @DisplayName("測試讀取header值:map形式")
    void send_map() throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("h1", "h1a");
        map.put("h2", "h2b");
        map.put("h3", "h3c");
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAll(map);

        MvcResult mvcResult = mockMvc.perform(get("/home/send")
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED))
                .andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        System.out.println("返回:"+content);
        assertThat(content, equalTo("res:h1a_h2b_h3c"));
    }
}

 

三,測試效果

1,訪問url

http://127.0.0.1:8080/home/home

如圖:

 

 

2,運行單元測試:

四,查看spring boot的版本:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.4)

 


免責聲明!

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



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