在上一篇中,我們對第一個自動化接口測試用例做了初步優化和斷言,這一篇我們處理POST請求。
4.1 發送POST方法請求
post方法和get方法是我們在做接口測試時,絕大部分場景下要應對的主要方法。
在發送請求時他們顯著的一個差別就在於,get方法我們只需要組在url內發送即可,post我們還需發送一個請求主體。
4.1.1 修改restfulClient實現發送POST請求
//通過httpclient獲取post請求的反饋 public void sendPost(String url, List<NameValuePair> params, HashMap<String, String> headers) throws ClientProtocolException, IOException{ //創建post請求對象 httpPost = new HttpPost(url);
//設置請求主體格式 httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//設置頭部信息 Set<String> set = headers.keySet(); for(Iterator<String> iterator = set.iterator(); iterator.hasNext();){ String key = iterator.next(); String value = headers.get(key); httpPost.addHeader(key, value); } httpResponse = httpclient.execute(httpPost); }
這里考慮用List來發送NameValuePair鍵值對來設置請求的主體。
頭部信息仍然采用哈希圖的方式設置。
其他接收反饋進行儲存和處理暫時不用做調整。
4.1.2 在測試類中測試
在src/test/java下新建testPost.java,代碼如下:
package com.test.api; import org.testng.annotations.Test; import com.alibaba.fastjson.JSONObject; import com.test.client.RestfulClient; import com.test.utils.JSONParser; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import org.testng.Assert; import org.testng.annotations.BeforeClass; public class testPost { RestfulClient client; JSONObject responseBody; JSONParser jParser; int responseCode; String city; String url = "https://api.apishop.net/communication/phone/getLocationByPhoneNum"; String postBody; @Test public void testPostRequest() {
//斷言反饋中城市信息是否正確 Assert.assertEquals(city, "北京");
//斷言反饋的狀態碼是否正確 Assert.assertEquals(responseCode, 200); } @BeforeClass public void beforeClass() throws ClientProtocolException, IOException { client = new RestfulClient();
//用NameValuePair的list來添加請求主體參數 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("apiKey", "nMke6NK29c40b1d******b3eec8aa0808389b16c4")); params.add(new BasicNameValuePair("phoneNum", "1861196136"));
//用哈希圖准備請求頭部信息 HashMap<String, String> hashHead = new HashMap<String, String>(); hashHead.put("Content-Type", "application/x-www-form-urlencoded");
//傳參發送post請求並接收反饋 client.sendPost(url, params, hashHead); responseBody = client.getBodyInJSON(); responseCode = client.getCodeInNumber(); System.out.println(responseBody); jParser = new JSONParser(); city = jParser.getCity(responseBody); } }
相較於前面測試get請求,最大的調整在於post請求我們設置了頭部信息和請求主體的參數。
4.1.3 TestNG測試結果
測試通過。
接下來的任務我們做進一步代碼優化、封裝,數據分離等。