我在 Spring Boot 应用程序的 JUnit 测试中使用 ObjectMapper 时遇到问题。
jackson 映射 POJO:
public Repository() {
@JsonProperty(value="fullName")
public String getFullName() {
return fullName;
}
@JsonProperty(value="full_name")
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonProperty(value = "cloneUrl")
public String getCloneUrl() {
return cloneUrl;
}
@JsonProperty(value = "clone_url")
public void setCloneUrl(String cloneUrl) {
this.cloneUrl = cloneUrl;
}
@JsonProperty(value="stars")
public int getStars() {
return stars;
}
@JsonProperty(value="stargazers_count")
public void setStars(int stars) {
this.stars = stars;
}
...
}
JUnit 测试:
@Autowired
private ObjectMapper objectMapper;
@Test
public void testWithMockServer() throws Exception{
Repository testRepository = new Repository();
testRepository.setCloneUrl("testUrl");
testRepository.setDescription("testDescription");
testRepository.setFullName("test");
testRepository.setStars(5);
String repoString = objectMapper.writeValueAsString(testRepository);
...
}
从 testRepository
创建字符串后,我发现并非每个字段都已设置 - 仅描述不需要任何附加 JsonProperty 映射。
这是因为 Repository
类中的 @JsonProperty
未被考虑在内。你知道如何修复它吗?
在 Controller 中,一切都运行良好。
restTemplate.getForObject(repoUrlBuilder(owner,repository_name),Repository.class);
最佳答案
(这是从 this answer over here 转述的)。
只有当您使用不同的属性并适本地委托(delegate)时,这才有效。通过您的代码,Jackson 找到同一属性的两个名称并选择一个:大概是 setter 方法上的名称,因为 Controller 中的解码正在为您工作。
您需要两个具有不同名称但具有相同值的属性。例如:
@JsonProperty(value="fullName")
public String getFullName() {
return fullName;
}
@JsonProperty(value="full_name")
public void setFull_Name(String fullName) { // Different property name here
this.fullName = fullName;
}
关于java - 如何在 JUnit 测试中使用 ObjectMapper - Spring Boot 应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45336982/