我有一个无法通过的测试用例:
ContactDTO contactDTO = generateContactDTO();
HttpEntity<ContactDTO> request = new HttpEntity<>(contactDTO, headers);
ResponseEntity<Response> response = restTemplate.exchange(generateBaseUrl() + "/contacts", HttpMethod.POST, request, Response.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
这是我的 ContactDTO 类:
public class ContactDTO {
@NotNull
@Size(min = 2, max = 100)
private String firstName;
@NotNull
@Size(min = 2, max = 100)
private String lastName;
@NotNull
@Size(min = 3, max = 100)
private String email;
@NotNull
@Size(min = 3, max = 50)
private String phoneNumber;
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
ContactDTO(@JsonProperty("firstName") @NotNull @Size(min = 2, max = 100) String firstName,
@JsonProperty("lastName") @NotNull @Size(min = 2, max = 100) String lastName,
@JsonProperty("email") @NotNull @Size(min = 3, max = 50) String email,
@JsonProperty("phoneNumber") @NotNull @Size(min = 3, max = 50) String phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}
String getFirstName() {
return firstName;
}
void setFirstName(String firstName) {
this.firstName = firstName;
}
String getLastName() {
return lastName;
}
void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
private void setEmail(String email) {
this.email = email;
}
String getPhoneNumber() {
return phoneNumber;
}
private void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
@PostMapping
public ResponseEntity<Response<String>> createContact(@Validated @RequestBody ContactDTO contactDTO, BindingResult bindingResult) {
if (bindingResult.getErrorCount() > 0) {
LOG.debug("Contact could not validated: {} and won't be created" +
" Validation error is as follows: {}", contactDTO, bindingResult);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new Response<>(Error.CONTACT_VALIDATION));
}
...
}
当我调试它时,我发现所有字段在发送到 Controller 之前都已填充在 contactDTO 中。但是,在 Controller 处,仅填充电子邮件字段,并导致 HTTP 错误请求。
PS:我使用 Spring Boot 2.1.7.RELEASE
最佳答案
由于没有公共(public)访问器,Jackson 无法序列化我的 DTO。因此,我将其添加到我的 DTO 对象顶部:
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
关于java - Spring Boot JUnit Jackson 无法反序列化所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818802/