2017-07-26 118 views
1

我在Spring Boot應用程序的JUnit測試中使用ObjectMapper時遇到了問題。如何在JUnitTests中使用ObjectMapper - Spring Boot應用程序

傑克遜映射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映射說明。 這是因爲@JsonPropertyRepository類沒有考慮。你知道如何解決它嗎? 在控制器中,一切都很好。

restTemplate.getForObject(repoUrlBuilder(owner,repository_name),Repository.class); 

回答

0

(這是解釋從this answer over here)。

只有在您使用不同的屬性並進行適當的委託時纔有效。在您的代碼中,Jackson爲同一個屬性找到兩個名稱並選擇一個:大概是setter方法中的名稱,因爲控制器中的解組正在爲您工作。

您需要具有不同名稱且具有相同值的兩個屬性。例如:

@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; 
} 
相關問題