今天,我需要為公共 API 使用者創(chuàng)建一個集成測試,并檢查我找到的記錄是否與查詢參數(shù)匹配。例如,我發(fā)送一個 GET 請求,例如localhost:8080/nutritionix/productDetails?query=grilled 我想找出包含“grilled”或“Grilled”或其他形式的相同短語的每個產(chǎn)品,例如:food_name 字段中的“GRillEd”短語。來自公共 API 的示例響應(yīng):[ { "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" } }]我想要實現(xiàn)的是檢查我在 JSON 響應(yīng)中收到的所有對象是否在 food_name 字段中包含一個短語,我們在查詢期間將其作為查詢參數(shù)傳遞,包括小寫和大寫字母以及有趣的文本大小寫。我想問題的出現(xiàn)是因為返回的記錄模式缺乏標(biāo)準(zhǔn)化,例如:有時我們得到帶有 food_name 字段的對象,它們是大寫的,有時是小寫的。感謝您提供有關(guān)如何改進(jìn)我的 JSONPath 語法的任何幫助。
1 回答

慕絲7291255
TA貢獻(xiàn)1859條經(jīng)驗 獲得超6個贊
問題是您正在檢查結(jié)果的任何元素是否等于grilled
。我認(rèn)為您需要檢查的是結(jié)果的每個元素是否都包含 grilled 忽略大小寫。
使用Hamcrest庫(我認(rèn)為您已經(jīng)在使用它),您可以通過以下方式進(jìn)行操作:
@Testpublic?void?everyContainsStringIgnoringCase()?{ ????List<String>?foodNames?=?JsonPath.read(RESPONSE,?"$[*].food_name"); ????assertThat(foodNames,?Every.everyItem(containsStringIgnoringCase("grilled"))); }
其中 RESPONSE 是你的 json。
添加回答
舉報
0/150
提交
取消