检查 JSON 响应中的每个对象是否包含特定字段中的短语

今天,我需要为公共 API 使用者创建一个集成测试,并检查我找到的记录是否与查询参数匹配。

例如,我发送一个 GET 请求,例如


localhost:8080/nutritionix/productDetails?query=grilled 

我想找出包含“grilled”或“Grilled”或其他形式的相同短语的每个产品,例如:food_name 字段中的“GRillEd”短语。


来自公共 API 的示例响应:


[

    {

        "food_name": "chicken grilled",

        "serving_qty": 1,

        "serving_unit": "piece",

        "photo": {

            "thumb": "https://d2xdmhkmkbyw75.cloudfront.net/1714_thumb.jpg"

        }

    },

    {

        "food_name": "grilled chicken thigh",

        "serving_qty": 1,

        "serving_unit": "thigh with skin",

        "photo": {

            "thumb": "https://d2xdmhkmkbyw75.cloudfront.net/8724_thumb.jpg"

        }

    },

    {

        "food_name": "grilled chicken wrap",

        "serving_qty": 1,

        "serving_unit": "wrap",

        "photo": {

            "thumb": "https://d2xdmhkmkbyw75.cloudfront.net/2562_thumb.jpg"

        }

    },

    {

        "food_name": "grilled cheese",

        "serving_qty": 1,

        "serving_unit": "sandwich",

        "photo": {

            "thumb": "https://d2xdmhkmkbyw75.cloudfront.net/1763_thumb.jpg"

        }

    },

    {

        "food_name": "Grilled Tilapia, Signature Grilled",

        "serving_qty": 1,

        "serving_unit": "fillet",

        "brand_name": "Gorton's",

        "nix_brand_id": "51db37b2176fe9790a8985bc",

        "photo": {

            "thumb": "https://d1r9wva3zcpswd.cloudfront.net/55178d395108f25f51667c2d.jpeg"

        }

    },

    {

        "food_name": "Grilled Gourmet Soft Taco, Grilled Chicken",

        "serving_qty": 189,

        "serving_unit": "g",

        "brand_name": "Amigos Kings Classic",

        "nix_brand_id": "521b95434a56d006cae297dc",

        "photo": {

            "thumb": "https://d2eawub7utcl6.cloudfront.net/images/nix-apple-grey.png"

        }

    }

]

我想要实现的是检查我在 JSON 响应中收到的所有对象是否在 food_name 字段中包含一个短语,我们在查询期间将其作为查询参数传递,包括小写和大写字母以及有趣的文本大小写。

我想问题的出现是因为返回的记录模式缺乏标准化,例如:有时我们得到带有 food_name 字段的对象,它们是大写的,有时是小写的。

感谢您提供有关如何改进我的 JSONPath 语法的任何帮助。



至尊宝的传说
浏览 82回答 1
1回答

慕丝7291255

问题是您正在检查结果的任何元素是否等于grilled。我认为您需要检查的是结果的每个元素是否都包含 grilled 忽略大小写。使用Hamcrest库(我认为您已经在使用它),您可以通过以下方式进行操作:@Testpublic void everyContainsStringIgnoringCase() {     List<String> foodNames = JsonPath.read(RESPONSE, "$[*].food_name");     assertThat(foodNames, Every.everyItem(containsStringIgnoringCase("grilled"))); }其中 RESPONSE 是你的 json。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java