zoukankan      html  css  js  c++  java
  • spring boot MockMVC的使用demo

    使用MockMVC进行带有参数的post访问

    package com.springboot.demo;
    
    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.MockHttpServletRequestBuilder;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class HelloWorldTest {
    
        private MockMvc mockMvc;
      //启用web上下文
        @Autowired
        private WebApplicationContext context;
      //使用上下文构建mockMvc
        @Before
        public void setUp(){
            mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
        }
      //存在controller,其访问路径为/hello,且带有一个参数name
        @Test
        public void getHello() throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=zhangsan")
                    .accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print());
        }
    }
    

    运行该单元测试,其运行结果为

    MockHttpServletRequest:
          HTTP Method = POST
          Request URI = /hello
           Parameters = {name=[zhangsan]}
              Headers = {Accept=[application/json;charset=UTF-8]}
                 Body = <no character encoding set>
        Session Attrs = {}
    
    Handler:
                 Type = null
    
    Async:
        Async started = false
         Async result = null
    
    Resolved Exception:
                 Type = org.springframework.web.HttpRequestMethodNotSupportedException
    
    ModelAndView:
            View name = null
                 View = null
                Model = null
    
    FlashMap:
           Attributes = null
    
    MockHttpServletResponse:
               Status = 405
        Error message = Request method 'POST' not supported
              Headers = {Allow=[GET]}
         Content type = null
                 Body = 
        Forwarded URL = null
       Redirected URL = null
              Cookies = []
    

      从上面我们可以看到访问方式,访问路径,参数,访问头,ModelAndView

  • 相关阅读:
    Spring aop 实现异常拦截
    drf 视图家族
    算法与数据结构
    接口
    Kubernetes
    drf
    drf 序列化
    drf 内部模块
    drf 接口
    vue
  • 原文地址:https://www.cnblogs.com/fengerlong/p/9039958.html
Copyright © 2011-2022 走看看