36

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

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();

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"

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.

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.

5
  • Can you provide more detail, like the config, real data you post to the server and some log detail to make it more clear? About the mock, it seems you are doing right, the param of mock test is the same kind of format of post data you show. Also, check if you have some think like spring security. You may need to mock spring security or perform login before do the next steps. Apr 12, 2016 at 10:02
  • 1
    We don't use anything like that, what I did find out is that my example is actually wrong. in this case someParam1 and someParam2 will be a query param, (In url). I want to make use of the form params hence URLENCODED. This however only seems to be accessible through a model or a value map. So we'll need a workaround (this was migrated to be fully spring mvc, used to be @FormParam which is not spring). Apr 12, 2016 at 10:22
  • Oh also the data posted, was like in my example below the Mvc part, it's posting a content string concatinated with & and = Apr 12, 2016 at 10:23
  • I dont know how you handle the post data in your controller, due to lack of detail. But base on the application form url encode, the param you post is correct format. The param here doesnt mean that only in url, it can be in post content too with the same format &name=value Apr 12, 2016 at 11:32
  • The very same setup works fine for me on Spring Boot 2.2.6. So, I assume they have fixed this in the meantime. Apr 11, 2020 at 10:38

4 Answers 4

35

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")
            )))));

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"
    ))));

With this helper function:

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();
 }
3
  • It's not the best, but it's a solution. Can you tell me why you need Apache HTTPComponents? As far as I can see this is achievable without any extra libraries. For now as the only answer I'll accept this, seems like it's hard to test in MockMVC Feb 28, 2017 at 14:51
  • 2
    Why do you think my solution is not good? You don't need HTTPComponents, I just used it because I had it on the classpath anyway. You can use any library that is able to construct an URL encoded form entity, which is nothing more than urlencode('name1') + '=' + urlencode(value1)+'&' + .... You could write your own helper method to construct it Mar 1, 2017 at 7:52
  • 2
    I think I meant it would be nicer if there was an implementation in mockMVC this works and is fine, but it remains t obe a workaround. Funny I see I replied after I haven't worked with Java for a while Oct 16, 2017 at 11:30
8

With modern spring (5.3.12) the offered solution didn't work. There seems to be a simple and elegant solution using the param method in MockHttpServletRequestBuilder:

    mockMvc.perform(post("/some/super/secret/url")
            .param("someparam1", true)
            .param("someparam2", false)
            .with(csrf())
    ).andExpect(status().isOk)

Note: As I am using using Spring Security I needed to add

.with(csrf())

So that the CSRF postProcessor allows my request. If not the Spring security would deny the request to avoid a Cross Site Request Forgery (CSRF) attack.

2

Here is a Kotlin SpringBoot example:

@RunWith(MockitoJUnitRunner::class)
class ApiFormControllerTest {

  lateinit var mvc: MockMvc

  @InjectMocks
  lateinit var apiFormController: ApiFormController

  @Before
  fun setup() {
    mvc = MockMvcBuilders.standaloneSetup(apiFormController).setControllerAdvice(ExceptionAdvice()).build()
  }

  fun MockHttpServletRequestBuilder.withForm(params: Map<String, String>): MockHttpServletRequestBuilder {
    this.contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .content(
            EntityUtils.toString(
                UrlEncodedFormEntity(
                    params.entries.toList().map { BasicNameValuePair(it.key, it.value) }
                )
            )
        )
    return this
  }

  @Test
  fun canSubmitValidForm() {
    mvc.perform(post("/forms").withForm(mapOf("subject" to "hello")))
        .andExpect(status().isOk)
  }

}
1

You could also use this small library I created: https://github.com/f-lopes/spring-mvc-test-utils/.

Add dependency in pom.xml:

<dependency>
    <groupId>io.florianlopes</groupId>
    <artifactId>spring-mvc-test-utils</artifactId>
    <version>1.0.1</version>
    <scope>test</scope>
</dependency>

Use it with MockMvc:

mockMvc.perform(MockMvcRequestBuilderUtils.postForm("/users", new AddUserForm("John", "Doe", null, new Address(1, "Street", 5222, "New York"))))
    .andExpect(MockMvcResultMatchers.status().isFound())
    .andExpect(MockMvcResultMatchers.redirectedUrl("/users"))
    .andExpect(MockMvcResultMatchers.flash().attribute("message", "success"));

This library simply adds the parameters to the MockMvc request, according to the form object.

Here is a detailed tutorial I wrote: https://blog.florianlopes.io/tool-for-spring-mockmvcrequestbuilder-forms-tests/

1

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.