How to test @ModelAttrbiute in spring boot controller test?

Viewed 106

i have a problem testing an endpoint which use @ModelAttribute I don't know very well how to test with this annotation and the test response is java.lang.AssertionError: Content type not set , here is the controller method:

@PostMapping
public ResponseEntity<?> createTestimonials(@ModelAttribute(name = "testimonialsCreationDto") @Valid TestimonialsCreationDto testimonialsCreationDto) {
        try {
             return ResponseEntity.status(HttpStatus.CREATED).body(iTestimonials.createTestimonials(testimonialsCreationDto));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
        }
    }

Here is the test:

@Test
    void createTestimonials() throws Exception {
        //Given
        String name = "Testimonio 159";
        String contentTestimonial = name + " content!";
        TestimonialsCreationDto testimonialsCreationDto = new TestimonialsCreationDto();
        testimonialsCreationDto.setName(name);
        testimonialsCreationDto.setContent(contentTestimonial);
        //When
        mockMvc.perform(post("/testimonials")
                .flashAttr("testimonialsCreationDto", testimonialsCreationDto)
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .content(objectMapper.writeValueAsString(testimonialsCreationDto))
                .characterEncoding("UTF-8"))
        //Then
                .andExpect(status().isCreated())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.name", is(name)))
                .andExpect(jsonPath("$.content", is(contentTestimonial)));
        verify(testimonialsService).createTestimonials(any());
    }
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /testimonials
       Parameters = {}
          Headers = [Content-Type:"multipart/form-data;charset=UTF-8", Content-Length:"74"]
             Body = {"name":"Testimonio 159","image":null,"content":"Testimonio 159 content!"}
    Session Attrs = {}

MockHttpServletResponse:
           Status = 200 ---> IDK why response with 200 code
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Content type not set

1 Answers

You have to add path value to PostMapping :

@PostMapping(path = "/testimonials", produces = MediaType.MULTIPART_FORM_DATA)
Related