我正试图在我的Spring Boot端点上运行一个测试,它接受来自客户端form
的信息,将输入字段映射到DTO并将其持久化到DB中,但我无法获得测试模式来接受它。据我所知,当你有一个这样定义的控制器端点时:
@PostMapping(path = "/newContact")
public @ResponseBody ContactDTO createNewContact(
@ModelAttribute ContactDTO newContact) {
//persists newContact to the data tier
}
@ModelAttribute标记将在传入的JSON名称中自动搜索newContact
DTO的字段名称,然后映射JSON值以填充DTO的各个字段。
这是我的ContactDTO类:
public class ContactDTO {
private BigInteger userId;
private BigInteger contactId;
private String name;
private String email;
private String bday;
private String address;
private String city;
private String state;
private List<PhoneDTO> phones;
private MultipartFile contactImgUpload;
//getters and setters
}
首先,这是正确的理解吗?
因此,我试图测试我的端点是否工作,方法是生成预期的DTO,但将其转换为JSON,然后将该JSON发布到控制器端点:
@Autowired
ObjectMapper objectMapper;
@Test
public void saveAnEntryWhenPOSTUserWithMultiplePhones() throws Exception {
List<PhoneDTO> phones = new ArrayList<>();
phones.add(new PhoneDTO("landline", "12312312312"));
phones.add(new PhoneDTO("mobile", "3242523462"));
ContactDTO cDTO = new ContactDTO();
cDTO.setContactId(BigInteger.valueOf(555));
cDTO.setName("Multiphone User");
cDTO.setUserId(BigInteger.valueOf(123));
cDTO.setEmail("test@email.com");
cDTO.setBday("01/01/1987");
cDTO.setState("IL");
cDTO.setCity("Chicago");
cDTO.setAddress("55 Jackson");
cDTO.setPhones(phones);
this.mockMvc.perform(post("/newContact")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(cDTO)))
.andExpect(status().isOk())
.andExpect(content().string(containsString(""phoneType":"landline:"")));
}
但当我这样做的时候,它显然没有以预期的方式发送JSON,因为当它试图保存到数据层时失败了,它说一些预期要填充的字段(这里的"名称"字段)是空的:
org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is javax.validation.ConstraintViolationException:
Validation failed for classes [app.models.relationentities.Contact] during
persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='may not be null',
propertyPath=name, rootBeanClass=class app.models.relationentities.Contact, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
那么,我的测试错了吗?如何模拟将填写好的表格发送到测试?
编辑包括电话DTO,这是ContactDTO字段private List<PhoneDTO> phones;
包含的列表:
public class PhoneDTO {
private String phoneType;
private String number;
//getters and setters
}
使用flashAttr
方法。
this.mockMvc.perform(post("/newContact")
.contentType(APPLICATION_JSON)
.flashAttr("newContact", cDTO))
.andExpect(status().isOk())
...
在控制器及其测试中也有不同的url:相应的/newContact
和/users/
。