基於Fitnesse的介面自動化測試-關鍵字設計-樣例-從Json中獲取指定值
阿新 • • 發佈:2020-08-04
需求
介面測試中,響應內容大部分是Json格式,需要校驗其中某些欄位值。
實現
1.編寫建構函式和成員變數
private String content;
public StringFixture() {
}
public StringFixture(String content) {
this.content = content;
}
2.實現方法(關鍵字)
public String getValueByKeyFromJsonString(String key) { String jsonContent = this.content; String value = null; if (null==jsonContent) { value = "json串為空"; } else { try { value = JsonUtil.getValue(jsonContent, key); } catch (JsonParseException e) { value = "JsonParseException"; logger.debug("JsonParseException:", e); } catch (IllegalStateException e) { value = "IllegalStateException"; logger.debug("IllegalStateException:", e); } catch (ClassCastException e) { value = "ClassCastException"; logger.debug("ClassCastException:", e); } catch (JSONException e) { value = "json串格式異常"; logger.debug("JSONException:", e); }catch(NullPointerException e){ value = "json串內容為空"; logger.debug("NullPointerException:", e); } logger.debug("jsonContent: {} , key: {} , value: {}", jsonContent, key, value); } return value; } public static String getValue(String jsonContent, String key) { String content = null; String value = null; System.out.println(jsonContent); if (jsonContent.contains("\\\"")) { content = jsonContent.replace("\"[\\\"", "[\""); content = content.replace("\"\\]\"", "\"]"); content = content.replace("\"{\\\"", "{\""); content = content.replace("\\\"}\"", "\"}"); content = content.replace("\\\"", "\""); } else { content = jsonContent; } JSONObject jsonObject = JSONObject.parseObject(content); if (jsonObject.containsKey(key)) { value = jsonObject.getString(key); } else { value = "json串中不包含欄位" + key; } return value; }
使用
1.引入類對應package
|import |
|own.slim.string|
2.編寫指令碼
|script |string fixture |{"status":"123","code":"345"} |
|$value=|getValueByKeyFromJsonString;|status |
|check |getValueByKeyFromJsonString;|code|345|
3.測試
總結
以上是處理簡單Json格式響應訊息的方法,這種方法也適用於處理資料庫的查詢結果。
如果遇到複雜的Json格式響應(巢狀或包含列表)或者其它格式,可以採用正則表示式來處理。