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)
原文地址:https://www.cnblogs.com/architectforest/p/14583603.html