1

I have problem with using ObjectMapper in JUnit tests in Spring Boot app.

Jackson mapping 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:

@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. That is because @JsonProperty from Repository class is not taken into account. Do you know how to fix it? In controller, everything works great.

restTemplate.getForObject(repoUrlBuilder(owner,repository_name),Repository.class);
Morfic
  • 15,178
  • 3
  • 51
  • 61
adamura88
  • 513
  • 1
  • 4
  • 13

1 Answers1

0

(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.

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;
}
Paul Hicks
  • 13,289
  • 5
  • 51
  • 78