【发布时间】: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