如何测试 属性 是否不存在 Spring Boot JacksonTester?

How to test if a property is not present with Spring Boot JacksonTester?

@JsonTest@Autowired JacksonTester 一起使用时,如何测试某个 属性 是否不存在?

假设您要序列化此对象:

@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 中是 而不是 当它是 null?

作为解决方法,我目前使用:

    assertThat(content).doesNotHave(new Condition<>(
            charSequence -> charSequence.toString().contains("myProperty"),
            "The property 'myProperty' should not be present"));

但这当然不完全一样。

您可以使用 JSON 路径断言来检查值,但是,您目前无法使用它来检查路径本身是否存在。例如,如果您使用以下内容:

JsonContent<MyTestObject> content = this.tester.write(new MyTestObject());
assertThat(content).hasEmptyJsonPathValue("myProperty");

{"myProperty": null}{} 都会通过。

如果你要测试 属性 存在但 null 你需要写这样的东西:

private Consumer<String> emptyButPresent(String path) {
    return (json) -> {
        try {
            Object value = JsonPath.compile(path).read(json);
            assertThat(value).as("value for " + path).isNull();
        } catch(PathNotFoundException ex) {
            throw new AssertionError("Expected " + path + " to be present", ex);
        }
    };
}

然后您可以执行以下操作:

assertThat(content.getJson()).satisfies(emptyButPresent("testProperty"));

顺便说一下,您的字符串断言也可以简化为:

assertThat(content.toString()).doesNotContain("myProperty");