【问题标题】:Junit mock test response blank bodyJunit 模拟测试响应空白正文
【发布时间】:2021-07-25 17:55:12
【问题描述】:

好吧,我在测试使用@ModelAttribute 的端点时遇到问题我不太清楚如何使用此注释进行测试,并且测试响应在 MockHttpServletResponse 中始终是一个空主体,但状态很好...

这里是控制器方法:

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
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());
    }
}

我的 dtos

@Getter @Setter @EqualsAndHashCode
public class TestimonialsCreationDto implements Serializable {
    private static final long serialVersionUID = 1L;
    @NotBlank(message = "{testimonials.error.empty.name}")
    private String name;
    private MultipartFile image;
    private String content;
}

@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public interface TestimonialsResponseDto {
    Long getId();
    String getName();
    String getImage();
    String getContent();
    Date getCreated();
    Date getEdited();
    Boolean getDeleted();
}

我的测试课

@Test
    void createTestimonials() throws Exception {
        //Given
        String name = "Testimonio 159";
        String contentTestimonial = name + " content!";
        Testimonials testimonials = new Testimonials();
        testimonials.setId(123L);
        testimonials.setName(name);
        testimonials.setContent(contentTestimonial);
        TestimonialsCreationDto testimonialsCreationDto = modelMapper.map(testimonials, TestimonialsCreationDto.class);
        TestimonialsResponseDto testimonialsResponseDto = projectionFactory.createProjection(TestimonialsResponseDto.class, testimonialsCreationDto);
        Mockito.when(testimonialsService.createTestimonials(Mockito.any(TestimonialsCreationDto.class))).thenReturn(Mockito.any(TestimonialsResponseDto.class));
        //When
        mockMvc.perform(post("/testimonials")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .flashAttr("testimonialsCreationDto", testimonialsCreationDto)
                .content(objectMapper.writeValueAsString(testimonialsCreationDto))
                .characterEncoding("UTF-8"))
        //Then
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.name", is(name)))
                .andExpect(jsonPath("$.content", is(contentTestimonial)));
        verify(testimonialsService).createTestimonials(isA(TestimonialsCreationDto.class));
    }

测试响应

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 = 201
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

【问题讨论】:

  • 你想在这里测试什么?基本上,您正在尝试测试您的应用程序是否启动?您应该测试 iTestimonials.createTestimonials 方法,或者您应该检查特定的 testimonialsCreationDto 对象是否会在正文中返回正确的 json

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


【解决方案1】:

我猜问题出在这一行,您在其中模拟了 TestimonialService 的行为:

Mockito.when(testimonialsService.createTestimonials(Mockito.any(TestimonialsCreationDto.class))).thenReturn(Mockito.any(TestimonialsResponseDto.class));

thenReturn() 部分在我看来是错误的。我希望您的模拟应该返回一个具体的TestimonialsResponseDto 对象。 你可以试试这样的:

when(testimonialsService.createTestimonials(any(TestimonialsCreationDto.class))).then(returnsFirstArg());

通过此设置,您的存储库将始终返回传递给它的 testimonialsService.createTestimonials(Mockito.any(TestimonialsCreationDto.class))

编辑 也许您想返回未在任何地方的代码中使用的testimonialsResponseDto

when(testimonialsService.createTestimonials(any(TestimonialsCreationDto.class))).then(testimonialsResponseDto);

如果您需要有关如何使用 @WebMvcTest 的示例,也许您会发现 this blog post of mine 很有帮助:)

【讨论】:

  • 我试过了,但还是出现了同样的错误,空正文 D:"java.lang.AssertionError: No value at JSON path "$.name""
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多