【问题标题】:How to test @ModelAttrbiute in spring boot controller test?如何在 Spring Boot 控制器测试中测试 @ModelAttrbiute?
【发布时间】:2021-07-23 21:49:13
【问题描述】:

我在测试使用 @ModelAttribute 的端点时遇到问题我不太清楚如何使用此注释进行测试,并且测试响应是 java.lang.AssertionError: Content type not set ,这是控制器方法:

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

这是测试:

@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:未设置内容类型

【问题讨论】:

  • 请仔细检查您的@PostMapping 路径是否为/testimonials
  • 是的,这就是路径
  • 太糟糕了,我也无法重现。

标签: java spring-boot unit-testing mockito junit5


【解决方案1】:

您必须将 path 值添加到 PostMapping :

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

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2017-10-03
    • 1970-01-01
    • 2017-06-08
    • 2019-06-22
    • 2021-02-08
    • 1970-01-01
    • 2017-01-04
    • 2016-06-02
    相关资源
    最近更新 更多