基于Fitnesse的接口自动化测试-关键字设计-样例-从Json中获取指定值
需求
接口测试中,响应内容大部分是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格式响应(嵌套或包含列表)或者其它格式,可以采用正则表达式来处理。
本文来自博客园,作者:月色深潭,交流群:733423266,转载请注明原文链接:https://www.cnblogs.com/moonpool/articles/13434455.html

浙公网安备 33010602011771号