zoukankan      html  css  js  c++  java
  • SpringBoot MockMvc的单元测试

    对于类的测试,可以有很多的方式进行实现,比如可以使用PostMan,使用HttpClient请求等,这里主要讲的是MockMcv的测试

    一:引入依赖

         <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
          </dependency>
    

      

    二:Demo如下:

    package cn.wangtao.controller;
    
    import cn.wangtao.HTTPEntity.RequestEntity.TestRequest;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.Assert;
    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.MvcResult;
    import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
    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;
    
    import java.util.HashMap;
    import java.util.Map;
    
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = cn.wangtao.run.Application.class)//注意这里的类要引入的是Main入口类
    public class TestControllerTest {
        @Autowired
        private WebApplicationContext context;
        private MockMvc mockMvc;
        private ObjectMapper objectMapper=new ObjectMapper();
    
        @Before
        public void setUp() {
            mockMvc = MockMvcBuilders.webAppContextSetup(context).build();  //构造MockMvc
        }
    
        @Test
        public void testModelParam() throws Exception {
            TestRequest request = new TestRequest();
            request.setAge(18);
            request.setName("桃子");
            request.setAddress("上海");
            request.setServerType("ctr1");
            Map<String, String> map = new HashMap<String, String>();
            map.put("request",objectMapper.writeValueAsString(request));
            modelParam("/test",objectMapper.writeValueAsString(request));
        }
    
        @Test
        public void testMoreParam() throws Exception {
            Map<String, String> map = new HashMap<String, String>();
            map.put("name","wangtao");
            map.put("age","18");
            map.put("address","上海");
            map.put("serverType","ctr2");
            moreParam("/test2",map);
        }
    
        /**
         * @Author wangtao
         * @Description  对象模型接收
         * @Date 2019-3-28  18:01
         * @Param param:对象的json 结构
         * @return
         **/
        public void modelParam(String requestPath, String param ) throws Exception {
            MockHttpServletRequestBuilder mockHttpServletRequestBuilder
                    = MockMvcRequestBuilders.get(requestPath)//自己选择方式
                                            .content(param)
                                            .contentType(MediaType.APPLICATION_JSON_UTF8);
            MvcResult result=mockMvc.perform(mockHttpServletRequestBuilder)
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andReturn();
            int statusCode = result.getResponse().getStatus();
            String content = result.getResponse().getContentAsString();
            System.out.println("statusCode: "+statusCode);
            System.out.println("返回结果 content: "+content);
            Assert.assertEquals(statusCode, 200);
        }
    
        /**
         * @Author wangtao
         * @Description  一个或多个k-参数
         * @Date 2019-3-28  17:59
         * @Param requestPath:URI, map:参数集合
         * @return
         **/
        public void moreParam(String requestPath, Map<String,String> map ) throws Exception {
            MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(requestPath);//请求方式自己定
            //参数封装
            for (Map.Entry<String,String> entry:map.entrySet() ){
                mockHttpServletRequestBuilder.param(entry.getKey(),entry.getValue());
            }
            mockHttpServletRequestBuilder.contentType(MediaType.APPLICATION_JSON_UTF8);
            MvcResult result=mockMvc.perform(mockHttpServletRequestBuilder)
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andReturn();
            int statusCode = result.getResponse().getStatus();
            String content = result.getResponse().getContentAsString();
            System.out.println("statusCode: "+statusCode);
            System.out.println("返回结果 content: "+content);
            Assert.assertEquals(statusCode, 200);
        }
      
    }
    

      

  • 相关阅读:
    浅析JavaScript正则表达式
    原生js格式化json工具
    你真的会玩SQL吗?无处不在的子查询
    你真的会玩SQL吗?EXISTS和IN之间的区别
    你真的会玩SQL吗?让人晕头转向的三值逻辑
    http://www.cnblogs.com/zhangs1986/p/4914520.html
    你真的会玩SQL吗?查询指定节点及其所有父节点的方法
    上传文件和导出的测试用例设计
    Fiddler抓取HTTPs流量
    Fiddler死活抓不了HTTPS包解决办法
  • 原文地址:https://www.cnblogs.com/gdhzdbh/p/9983503.html
Copyright © 2011-2022 走看看