Search code examples
spring-bootmockmvcspring-test-mvc

How test Post request with custom object in content type application/x-www-form-urlencoded?


I have controller:

    @PostMapping(value = "/value/", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public String updateSettings(final Dto dto) {
        System.out.println(">>> " + dto);
        return "template";
    }

Controller works if I send request across chrome window. But when I write test for this method I get problem. Not converted object, value not inserted.

Test:

@Test
    @WithMockUser(username = FAKE_VALID_USER, password = FAKE_VALID_PASSWORD)
    public void test_B_CreateDtoWithValidForm() throws Exception {

        final Dto dto = new Dto();
               dto.setId("value");
               dto.setEnabled("true");

        this.mockMvc.perform(post(URL_SET_PROVIDER_SETTINGS)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                .content(dto.toString()))
                    .andDo(print());
  }

Output is >>> Dto{id=null, enabled=false}

How test Post request with custom object in content type application/x-www-form-urlencoded?


Solution

  • In this case you don't need to use content, but instead you need to use param in this way:

    this.mockMvc.perform(post(URL_SET_PROVIDER_SETTINGS)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                .param("id", "value")
                .param("enabled", "true"))
                .andDo(print());