接口測試中如何使用Json 來進行數(shù)據(jù)交互 ?
本文節(jié)選自霍格沃茲測試開發(fā)學(xué)社內(nèi)部教材
json 是一種輕量級的傳輸數(shù)據(jù)格式,用于數(shù)據(jù)交互。json 請求類型的請求頭中的?Content-Type
?對應(yīng)為?application/json
?。碰到這種類型的接口,使用 Java 的 REST Assured 或者 Python 的 Requests 均可解決。
實戰(zhàn)演示
在 Python 中,使用 json 關(guān)鍵字參數(shù)發(fā)送 json 請求并傳遞請求體信息。
>>> import requests
>>> r = requests.post(
? 'https://httpbin.ceshiren.com/post',
? json = {'key':'value'})
>>> r.request.headers
{'User-Agent': 'python-requests/2.22.0',
'Accept-Encoding': 'gzip, deflate',\
'Accept': '*/*', 'Connection': 'keep-alive',
'Content-Length': '16',\
?'Content-Type': 'application/json'}
如果請求的參數(shù)選擇是json
?,那么Content-Type
?自動變?yōu)?code>application/json?。
在 Java 中,使用contentType()方法添加請求頭信息,使用body()方法添加請求體信息。
import static org.hamcrest.core.IsEqual.equalTo;
import static io.restassured.RestAssured.*;
public class Requests {
? ?public static void main(String[] args) {
? ? ? ?String jsonData = "{\"key\": \"value\"}";
? ? ? ?//定義請求頭信息的contentType為application/json
? ? ? ?given().contentType("application/json").
? ? ? ? ? ? ? ?body(jsonData).
? ? ? ? ? ? ? ?when().
? ? ? ? ? ? ? ?post("https://httpbin.ceshiren.com/post").
? ? ? ? ? ? ? ?then().body("json.key", equalTo("value")).log().all();
? ?}
}