3 votes

Comment tester @ModelAttrbiute dans un test de contrôleur Spring Boot ?

J'ai un problème pour tester un endpoint qui utilise @ModelAttribute Je ne sais pas très bien comment tester avec cette annotation et la réponse du test est java.lang.AssertionError : Type de contenu non défini Voici la méthode du contrôleur :

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

Voici le 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 : Type de contenu non défini

0voto

Vous devez ajouter path à PostMapping :

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

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X