[英]How to use ObjectMapper in JUnitTests - Spring Boot app
I have problem with using ObjectMapper in JUnit tests in Spring Boot app. 我在Spring Boot应用程序的JUnit测试中使用ObjectMapper有问题。
Jackson mapping POJO: 杰克逊映射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 tests: 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);
...
}
After creating String from testRepository
I see that not every field is set up - only description which do not require any addition JsonProperty mapping. 从
testRepository
创建String之后,我看到不是所有字段testRepository
设置-仅是描述,不需要任何其他JsonProperty映射。 That is because @JsonProperty
from Repository
class is not taken into account. 这是因为未考虑来自
Repository
类的@JsonProperty
。 Do you know how to fix it? 你知道怎么解决吗? In controller, everything works great.
在控制器中,一切正常。
restTemplate.getForObject(repoUrlBuilder(owner,repository_name),Repository.class);
(This is paraphrased from this answer over here ). (这是这里答案的解释)。
This works only if you use different properties and delegate appropriately. 仅当您使用其他属性并适当委托时,此方法才有效。 With your code, Jackson finds two names for the same property and picks one: presumably, the name on the setter methods, since the unmarshalling in the controller is working for you.
使用您的代码,Jackson会为同一属性找到两个名称,然后选择一个:大概是setter方法上的名称,因为控制器中的解组对您有用。
You need two properties with different names and which have the same value. 您需要两个名称不同且值相同的属性。 For example:
例如:
@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.