Search code examples
spring-mvchttp-postbean-validationspring-test-mvc

Spring MockMVC for Post Request and Bean Validation


i have a common problem to test Post-Request with Bean Validation.

Requirements: ContentType is APPLICATION_FORM_URLENCODED and NOT JSON

Model under test:

public class Message extends Auditable{

    @Id
    private long id;    
    private String messageText;
    @NotNull
    private Link link;
}

How it works on browser properly: I'am just submit data. On Browser Dev-Tools, i see, that browser sends only to fields: messageText="my message" and link="1"

problem: during MockMVC Post-Request, i can not convert param-value "1" to the object Link.

   this.mockMvc.perform(MockMvcRequestBuilders.post("/links/link/comments")
                                                    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                                                    .param("link", "1")
                                                    .param("messageText", "hello message"))

                    .andDo(print())
                    .andExpect(status().is3xxRedirection());

}

My post-handler on controller

@PostMapping(value = "/link/message")
public String saveNewComment(@Valid Message message, BindingResult bindingResult, RedirectAttributes attributes) {      

    if(bindingResult.hasErrors()) {                         
            model.addAttribute("newMessage", message);
            return "link/submit";
    } 
}

BindingResult complains about TypeMismatch from "String" to "Link".

How can i pass some Marschal- or Converter-Object, which enables BindingResult to convert string-value to appropriate object?

I don't want to implement on server-side own validator-object (which implements validator interface), cause on production it works properly without any additional code.


Solution

  • I've solved this issue by myself with small fix. Nested objects should parameterize with explizit field-name. Instead of param("link", "1") it must be param("link.id", "1")