java - 如何在 JUnit 测试中使用 ObjectMapper - Spring Boot 应用

标签 java spring-boot junit jackson objectmapper

我在 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/

相关文章:

java - for循环后返回

java - 关闭 session 后立即触发 destroyListener

java - 如何防止spring-web的spring-boot自动配置?

java - Apache Camel 路由中的 Spring Boot 属性使用

java - 从spring执行sql脚本时"user lacks privilege or object not found"

Java JAX-RS 对任何端点调用使用react

java - Guava缓存asMap方法

java - Spring Web服务删除响应字符串中的多个空格

eclipse - 有没有办法在不使用 jvm 代理的情况下使用 Spring AspectJ LTW 运行 JUnit 4 测试?

jenkins - Jenkins 上的 JUnit 结果超过 1 个图表