我們?cè)谧鰆meter接口測試時(shí)能會(huì)用beanshell斷言秦士,一般都會(huì)將返回值轉(zhuǎn)成JSONObject對(duì)象進(jìn)行處理销斟。本文選取較為復(fù)雜json格式數(shù)據(jù)祭玉,也將適用于java接口測試箱熬。
JSON數(shù)據(jù)
{
"data": {
"city": "深圳",
"date": "2017-11-04",
"pm25": {
"aqi": 0,
"co": 8,
"updatetime": "2017-11-04 13:00:00"
},
"daily": [
{
"date": "2017-11-04",
"week": "星期六",
"templow": "19",
"weather": "多云"
},
{
"date": "2017-11-05",
"week": "星期日",
"sunrise": "06:29",
"weather": "多云"
}
]
},
"status": 0,
"msg": "ok"
}
解析JSON
以下代碼使用HttpClient進(jìn)行接口測試馁害,同時(shí)使用testNg進(jìn)行斷言
package apitest.cases;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.net.URI;
public class Weather {
@Test
public void weather() {
HttpClient httpClient = HttpClientBuilder.create().build();
//執(zhí)行post方法
try {
HttpGet httpGet = new HttpGet();
httpGet.setURI(URI.create("http://localhost:8001/weather"));
//聲明一個(gè)對(duì)象來進(jìn)行響應(yīng)結(jié)果的存儲(chǔ)
HttpResponse response = httpClient.execute(httpGet);
//獲取響應(yīng)結(jié)果將格式轉(zhuǎn)化為Json數(shù)據(jù)
String response2 = EntityUtils.toString(response.getEntity(), "utf-8");
JSONObject responseJson = new JSONObject(response2);
// 獲取msg status
String msg = responseJson.getString("msg");
String status = responseJson.get("status").toString();
// 獲取data
JSONObject jsonData = responseJson.getJSONObject("data");
// 獲取data里的city
String city = jsonData.getString("city");
// 獲取pm25
JSONObject pm25 = jsonData.getJSONObject("pm25");
// 獲取pm25里的updatetime
String updateTime = pm25.getString("updatetime");
// 獲取data里的daily
JSONArray jsonDaily = jsonData.getJSONArray("daily");
// 獲取data里的daily的第一組數(shù)據(jù)
JSONObject jsonDailyFirst = jsonDaily.getJSONObject(0);
// 獲取data里的daily的第一組數(shù)據(jù)的date
String date = jsonDailyFirst.getString("date");
System.out.println("獲取msg----" + msg);
System.out.println("獲取status----" + status);
System.out.println("獲取data----" + jsonData);
System.out.println("獲取data里的city----" + city);
System.out.println("獲取pm25----" + pm25);
System.out.println("獲取pm25里的updateTime----" + updateTime);
System.out.println("獲取data里的daily----" + jsonDaily);
System.out.println("獲取data里的daily的第一組數(shù)據(jù)----" + jsonDailyFirst);
System.out.println("獲取data里的daily的第一組數(shù)據(jù)的date----" + date);
//斷言
Assert.assertEquals(msg, "ok");
} catch (Exception e) {
e.printStackTrace();
}
}
}
歡迎關(guān)注微信公眾號(hào):軟件測試汪窄俏。軟件測試交流群:809111560
轉(zhuǎn)載請(qǐng)注意出處,謝謝合作