代码之家  ›  专栏  ›  技术社区  ›  Wim Deblauwe

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

  •  0
  • Wim Deblauwe  · 技术社区  · 5 年前

    当使用 @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"));
    

    但这当然不完全相同。

    0 回复  |  直到 5 年前
        1
  •  1
  •   Phil Webb    5 年前

    您可以使用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");