0

I have the following controller method

 @PostMapping("/create")
    public ModelAndView createDocument(@ModelAttribute("user") @Valid User userToSave, BindingResult bindingResult,@RequestParam String adressId,@RequestParam MultipartFile file){

Now I want to create a integration test which supplies the following parameters. But I always get a 403. My testmethod looks like that:

@Test
    @WithMockUser(username = "user",password = "user123",roles="ADMIN")
    public void testUploadDocument() throws Exception {
User mockUser = new User("User",null,null,"test comment","Dies ist ein Test");
MockMultipartFile file
            = new MockMultipartFile(
            "file",
            "hello.txt",
            MediaType.TEXT_PLAIN_VALUE,
            "Hello, World!".getBytes()
        );
this.mockMvc.perform(MockMvcRequestBuilders.multipart("/create").file(file).param("adressId", "96cf9ec3-f820-4192-a4db-920328df5ff4")
                .param("file", objectMapper.writeValueAsString(mockUser))
            ).andDo(print()).andExpect(status().isOk())
            .andExpect(view().name(containsString("list")));
}

1 Answers1

0

I know this is very late to reply however if someone else with the same issue finds this answer then the world may be a little brighter.

You need to adjust your perform() call to include csrf() handling, i.e. change it to:

this.mockMvc.perform(MockMvcRequestBuilders.multipart("/create").file(file).param("adressId", "96cf9ec3-f820-4192-a4db-920328df5ff4")
                .param("file", objectMapper.writeValueAsString(mockUser))
    .with(csrf())
            )

Then you should be good.

David Brown
  • 3,021
  • 3
  • 26
  • 46