通过MockMVC测试表单帖子 [英] Testing Form posts through MockMVC

查看:282
本文介绍了通过MockMVC测试表单帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写测试以验证是否可以将通用表单发布到我们的API.

I'm writing tests to verify that I can do a generic form post to our API.

我还添加了一些调试功能,但是我注意到数据是通过实际表格发布的; (邮递员/AngularJS或w/e)与进行模拟MVC测试不同,例如:

I've also added quite some debugging, but I noticed that the data posted by an actual form; (Postman / AngularJS or w/e) Differs from doing a mockMVC test like:

MvcResult response = mockMvc
            .perform(post("/some/super/secret/url") //
                    .param("someparam1", "somevalue") //
                    .param("someparam2", "somevalue") //                
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED) //
                    .accept(MediaType.APPLICATION_JSON)) //
            .andExpect(status().isOk()) //
            .andReturn();

该配置与生产环境中运行的配置完全相同,依此类推.但是,当我的拦截器记录内容时,在实际测试中(而不是嘲笑MVC),内容的格式类似于"someparam1 = somevalue& etc = encore"

The config is exactly the same as the config running in production, and such. However When my interceptor logs the content, in real test (not mockMVC) the content is formatted like "someparam1=somevalue&etc=encore"

当我打印mockMVC内容时,我实际上似乎没有内容,但是请求中包含Params,我假设它们像GET参数一样被添加.

When I print the mockMVC content I actually seem to have no content, but there are Params in the request, I assume they're added like GET parameters.

有人知道如何正确测试吗?我遇到了这个问题,因为即使我们已经将FormHttpMessageConverter添加到Servlet上下文中,我们的表单帖子似乎也没有被Spring解析.

Anyone know how to properly test this? I came upon this issue since it seems like our form posts don't seem to be parsed by Spring even though we have the FormHttpMessageConverter added to the servlet context.

推荐答案

如果您的类路径上有Apache HTTPComponents HttpClient,则可以这样操作:

If you have Apache HTTPComponents HttpClient on your classpath, you can do it like this:

    mockMvc.perform(post("/some/super/secret/url")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .content(EntityUtils.toString(new UrlEncodedFormEntity(Arrays.asList(
                    new BasicNameValuePair("someparam1", "true"),
                    new BasicNameValuePair("someparam2", "test")
            )))));

如果您没有HttpClient,则可以使用一个简单的辅助方法来构造它,该方法可以构造urlencoded表单实体:

If you don't have HttpClient, you can do it with a simple helper method that constructs the urlencoded form entity:

    mockMvc.perform(post("/some/super/secret/url")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .content(buildUrlEncodedFormEntity(
         "someparam1", "value1", 
         "someparam2", "value2"
    ))));

具有此辅助功能:

private String buildUrlEncodedFormEntity(String... params) {
    if( (params.length % 2) > 0 ) {
       throw new IllegalArgumentException("Need to give an even number of parameters");
    }
    StringBuilder result = new StringBuilder();
    for (int i=0; i<params.length; i+=2) {
        if( i > 0 ) {
            result.append('&');
        }
        try {
            result.
            append(URLEncoder.encode(params[i], StandardCharsets.UTF_8.name())).
            append('=').
            append(URLEncoder.encode(params[i+1], StandardCharsets.UTF_8.name()));
        }
        catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    return result.toString();
 }

这篇关于通过MockMVC测试表单帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆