前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MockMvc -你需要一个测试基类

MockMvc -你需要一个测试基类

作者头像
Criss@陈磊
发布2019-09-17 16:50:37
1K0
发布2019-09-17 16:50:37
举报
文章被收录于专栏:测试技术圈测试技术圈

现有MockMvc用例

该用例的测试场景是:

  1. 向服务端发送一个post请求,来创建一个新的TestLink的keyword。 2)向服务端发送一个get请求,来获取刚才创建的新的TestLink的keyword。 3)验证keyword创建前后的内容是否一致。
代码语言:javascript
复制

public class KeywordsControllerTest extends TestBase{

     protected MockMvc mockMvc;

        @Autowired
        protected WebApplicationContext wac;

        @Before()
        public void setup() {
            mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //初始化MockMvc对象
        }
  @Test 
  public void CreateKeywordsAndQueryTest() throws UnsupportedEncodingException, Exception {
      Keywords keywords=Keywords.builder().keyword("tester").testproject_id(333).notes("tester").build();
      String jsonString = JSON.toJSONString(keywords);
            String responseString = mockMvc.perform(
                    post("/api/keywords")    //请求的url,请求的方法是post                            .contentType(MediaType.APPLICATION_JSON)  //数据的格式
                            .content(jsonString)      //body
            ).andExpect(status().isOk())    //返回的状态是200
                    .andDo(print())         //打印出请求和相应的内容
                    .andReturn().getResponse().getContentAsString();   //将相应的数据转换为字符串
            System.out.println("responseString::"+responseString);
            assertThat(responseString).isNotEqualTo(1);

            String response = mockMvc.perform(
                    get("/api/keywords/?id="+responseString)    //请求的url,请求的方法是get
                            .contentType(MediaType.APPLICATION_JSON)  //数据的格式
            ).andExpect(status().isOk())    //返回的状态是200
                    .andDo(print())         //打印出请求和相应的内容
                    .andReturn().getResponse().getContentAsString();   //将相应的数据转换为字符串
            keywords.setId(Integer.parseInt(responseString));
            String jsonString2 = JSON.toJSONString(keywords);
          assertEquals(response,jsonString2,true);
          //  assertThat(response).asString().isEqualTo(jsonString2);
  }
  }

用例虽然能执行成功,但是还存在着不少问题。最为严重的,就是代码冗余度太高。两次模拟的HTTP请求,虽然请求的方式和发送内容不同,但是整个请求的组装、发送和结果验证过程是基本一致的。因此,我们可以考虑重构上述用例,将公共部分提取到父类中供其余测试用例使用。

MockMvc测试基类

首先将mockMvc、WebApplicationContext 的实例提取到基类中。

代码语言:javascript
复制
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Profile("ut")
public class TestBase {
     protected MockMvc mockMvc;
        @Autowired
        protected WebApplicationContext wac;

        @Before()
        public void setup() {
            mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //初始化MockMvc对象
        }
        

封装Http请求

需求: 提供doPost、doGet等需求,让用例编写人员直接输入URL、请求参数等基本类型,不再需要与MockMvc打交道了。

代码语言:javascript
复制
        private String doRequest(RequestBuilder builder) throws UnsupportedEncodingException, Exception {
            return  mockMvc.perform(builder)
                    .andDo(print())
                    .andExpect(status().isOk())    //返回的状态是200
                            //打印出请求和相应的内容
                    .andReturn().getResponse().getContentAsString();
        }
        
        private MockHttpServletRequestBuilder performPostWithBody(String url,String body) {
            return MockMvcRequestBuilders
                    .post(url)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content(body);
        }
        private MockHttpServletRequestBuilder performGetWithParams(String url,MultiValueMap<String, String> params) {
            return MockMvcRequestBuilders
                    .get(url)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .params(params);
        }
        
        public String doPost(String url,String body) throws UnsupportedEncodingException, Exception {
            return doRequest(performPostWithBody( url, body));
        }
        public String doGet(String url,MultiValueMap<String, String> params) throws UnsupportedEncodingException, Exception {
            return doRequest(performGetWithParams( url, params));
        }

在工程实践中,一般还需要在head中增加user-agent、cookie等信息。在RequestBuilder 中构造即可。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-09-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 质问 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 现有MockMvc用例
  • MockMvc测试基类
  • 封装Http请求
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档