今天,我需要為公共 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 語法的任何幫助。
1 回答

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