简体   繁体   English

AssertJ JSON 属性检查

[英]AssertJ JSON property check

I have JSONObject instance which contains some property,我有 JSONObject 实例,其中包含一些属性,

{
"name":"testName",
"age":"23"
}

i use the following assert, but it fails.我使用以下断言,但它失败了。 Is this correct approach to test JSON in assertj.这是在 assertj 中测试 JSON 的正确方法吗?

assertThat(jsonObject).hasFieldOrProperty("name");

如果你想对 JSON 对象做任何严肃的断言,我会推荐 JsonUnit https://github.com/lukas-krecan/JsonUnit

I think it has to do with the fact the JSONObject is like a map which has key-value pairs, while AssertJ expects Java bean-style objects to check if a property exists.我认为这与JSONObject就像一个具有键值对的映射这一事实有关,而 AssertJ 期望 Java bean 样式的对象检查属性是否存在。 I understood this from the document at https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/AbstractObjectAssert.html#hasFieldOrProperty(java.lang.String) .我从https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/AbstractObjectAssert.html#hasFieldOrProperty(java.lang.String)的文档中了解到这一点。 Hope I am looking at the right place.希望我找对地方了。

I mean to say that a map or JSONObject doesn't have fields declared in it for AssertJ to look for.我的意思是说地图或JSONObject中没有声明字段供 AssertJ 查找。

You may use JSONObject.has( String key ) instead, I think.我想你可以改用JSONObject.has( String key )

Fist, you need to traverse the keysets (nodes) using the map class, then verify if the keyset contains the particular node you are looking for.首先,您需要使用map类遍历键集(节点),然后验证键集是否包含您要查找的特定节点。

Map<String, Object> read = JsonPath.read(JSONObject, "$");
assertThat(read.keySet()).contains("name");

If you use SpringBoot you can use the custom impl.如果您使用 SpringBoot,则可以使用自定义 impl。 for Assertj 对于断言

    private final BasicJsonTester json = new BasicJsonTester(getClass());

    @Test
    void testIfHasPropertyName() {
        final JSONObject jsonObject = new JSONObject("{\n" +
                "\"name\":\"testName\",\n" +
                "\"age\":\"23\"\n" +
                "}");
        
        assertThat(json.from(jsonObject.toString())).hasJsonPath( "$.name");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM