Spring boot 如何测试Spring Boot JacksonTester是否不存在属性?
将Spring boot 如何测试Spring Boot JacksonTester是否不存在属性?,spring-boot,spring-boot-test,assertj,Spring Boot,Spring Boot Test,Assertj,将@JsonTest与@Autowiredjacksontest一起使用时,如何测试某个属性是否不存在 假设要序列化此对象: @JsonInclude(JsonInclude.Include.NON_NULL) public class MyTestObject { private Boolean myProperty; // getter and setter } 通过此测试: @RunWith(SpringRunner.class) @JsonTest public cl
@JsonTest
与@Autowired
jacksontest
一起使用时,如何测试某个属性是否不存在
假设要序列化此对象:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyTestObject {
private Boolean myProperty;
// getter and setter
}
通过此测试:
@RunWith(SpringRunner.class)
@JsonTest
public class MyTestObjectTest {
@Autowired
private JacksonTester<MyTestObject> tester;
public void testPropertyNotPresent() {
JsonContent content = tester.write(new MyTestObject());
assertThat(content).???("myProperty");
}
}
但是这当然不完全相同。您可以使用JSON路径断言来检查值,但是,您当前不能使用它来检查路径本身是否存在。例如,如果使用以下选项:
JsonContent<MyTestObject> content = this.tester.write(new MyTestObject());
assertThat(content).hasEmptyJsonPathValue("myProperty");
assertThat(content.getJson()).satisfies(emptyButPresent("testProperty"));
然后,您可以执行以下操作:
JsonContent<MyTestObject> content = this.tester.write(new MyTestObject());
assertThat(content).hasEmptyJsonPathValue("myProperty");
assertThat(content.getJson()).satisfies(emptyButPresent("testProperty"));
顺便提一下,您的字符串断言也可以简化为:
assertThat(content.toString()).doesNotContain("myProperty");
不幸的是,这不是真的。如果属性存在一个
null
值,测试不会失败。奇怪的是,我以为我已经测试过了。你有一个我可以尝试的示例项目吗?我在创建了一个示例项目。您将看到testJsonWithNull\u doesNotContain
会失败,而testJsonWithNull\u hassemptyjsonpathvalue
不会失败,如果@JsonInclude(JsonInclude.Include.NON\u NULL)
在测试对象上不存在我现在看到,您想检查该值是否为NULL
,但是属性名仍然在JSON中。我已经更新了答案,以说明如何做到这一点。如果您想提出Spring启动问题,我们可以考虑添加另一个断言方法。感谢您提出这个问题。从boot2.2开始,您将能够执行assertThat(content.doesNotHaveJsonPath(“myProperty”)
。