1. 程式人生 > >java介面自動化3——POST請求方法封裝過程和測試

java介面自動化3——POST請求方法封裝過程和測試

這個介面自動化測試框架到目前為止,我們已經完成了Get請求的封裝和必要的工具類的支援。接下來這篇,我來介紹如何完成POST請求的封裝過程。一般來說,在一個專案中,介面測試很多時候就是測試Get和POST方法,其他的請求方式的介面很少,佔的比重幾乎不計。所以,這個Java介面自動化測試框架的核心就是Get和POST請求方法的封裝過程。

 

1.POST介面舉例

瀏覽器開啟https://reqres.in/,下拉一屏。點選第一個POST請求,這個介面的介紹資訊如下。

      這個介面的作用是建立使用者,引數是一個json型別的資料,一個name一個job,兩個JSON物件。傳送請求之後,返回的JSON資料有name和job和id,以及建立時間這幾個資料。

 

2.Postman手動實現

 

我們先在本地postman環境,先來手動測試實現下這個post介面的請求過程。

這個post介面請求還是比較簡單,很容易在postman上實現該請求。

 

3.Java程式碼自動化實現

 

       我們已經可以正確地在postman上實現建立使用者這個介面的手動測試,那麼我們想要這個過程自動化實現,如何做呢。下面我在RestClient.java封裝了兩個方法,一個是帶請求頭資訊的Get請求,一個是帶請求頭資訊的POST請求方法。這篇,瞭解了POST請求方法,帶請求頭的Get方法封裝就很好理解。

package com.qa.restclient;


import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class RestClient {

    //重構後Get方法:
    public CloseableHttpResponse get(String url) throws ClientProtocolException,IOException{
        //建立一個可關閉的HttpClient物件
        CloseableHttpClient httpclient=HttpClients.createDefault();
        //建立一個HttpGet的請求物件
        HttpGet httpget=new HttpGet(url);
        //執行請求,相當於jmeter上點選執行按鈕,然後賦值給HttpResponse物件接收
        CloseableHttpResponse httpResponse=httpclient.execute(httpget);

        return httpResponse;

    }
    //2. Get 請求方法(帶請求頭資訊)
    public CloseableHttpResponse get(String url, HashMap<String,String> headermap) throws ClientProtocolException, IOException{
        //建立一個可關閉的HttpClient物件
        CloseableHttpClient httpclient=HttpClients.createDefault();
        //建立一個HttpGet的請求物件
        HttpGet httpget=new HttpGet(url);

        //載入請求頭到httpget物件
        for(Map.Entry<String,String> entry:headermap.entrySet()){
            httpget.addHeader(entry.getKey(),entry.getValue());
        }
        //執行請求,相當於postman上點擊發送按鈕,然後賦值給HttpResponse物件接收
        CloseableHttpResponse httpResponse=httpclient.execute(httpget);
        return httpResponse;

    }

    //3. POST方法
    public CloseableHttpResponse post(String url,String entityString,HashMap<String,String> headermap) throws ClientProtocolException, IOException{
        //建立一個可關閉的HttpClient物件
        CloseableHttpClient httpclient=HttpClients.createDefault();
        //建立一個HttpPost的請求物件
        HttpPost httppost=new HttpPost(url);
        //設定請求引數,post請求的body部分;setEntity(),()中是一個httpEntity;get請求沒有body部分,請求引數都在header中所以沒用setEntity()這個方法
        httppost.setEntity(new StringEntity(entityString));
        //載入請求頭到httppost物件,post請求的頭部分,如果報文格式是json還是xml等
        for(Map.Entry<String,String> entry:headermap.entrySet()){
            httppost.addHeader(entry.getKey(),entry.getValue());
        }
        //傳送post請求
        CloseableHttpResponse httpResponse=httpclient.execute(httppost);
        return httpResponse;

    }

}

    然後,我們需要寫一個TestNG測試用例來測試下這個封裝的post方法好不好用。由於我們去前面幾篇文章介紹了TestNG測試get方法的程式碼,這裡我們就直接拷貝和修改部分程式碼就行。

      在寫測試用例之前,我們需要提前準備好json資料,一般來說,在Java中JSON資料都是放在JAVA Bean類中,通過JSON把高階物件序列化成JSON物件。

      在src/main/java中新建包:com.qa.data,然後新建一個Users.java,這個命名就參考介面的url單詞就行。在postman或者網站該post方法,我們知道,需要name和job這兩個json物件。我們新建一個bean類,同alt+shift+s,然後選擇生成構造方法和set和get方法。

package com.qa.data;
 
public class Users {
 
	private String name;
	private String job;
	
	public Users() {
		super();
	}
 
	public Users(String name, String job) {
		super();
		this.name = name;
		this.job = job;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public String getJob() {
		return job;
	}
 
	public void setJob(String job) {
		this.job = job;
	}
	
}

     好了,在src/test/java下的com.qa.tests我們新建一個POST測試用例,現在我們的TestNG測試類程式碼如下:

​
package com.qa.tests;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qa.base.TestBase;
import com.qa.data.Users;
import com.qa.restclient.RestClient;
import com.qa.util.TestUtil;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.HashMap;

public class PostApiTest extends TestBase {
    TestBase testBase;
    String host;
    String url;
    RestClient restClient;
    CloseableHttpResponse closeableHttpResponse;

    @BeforeClass
    public void setUp(){
        testBase=new TestBase();
        host=prop.getProperty("HOST");
        url=host+"/api/users";
    }

    @Test
    public void postApiTest() throws ClientProtocolException, IOException {
        restClient=new RestClient();

        HashMap<String,String> headermap=new HashMap<String,String>();

        headermap.put("Content-Type","application/json");
        Users user=new Users("navy","tester");
        String userJsonString= JSON.toJSONString(user);

        closeableHttpResponse=restClient.post(url,userJsonString,headermap);

        int statusCode=closeableHttpResponse.getStatusLine().getStatusCode();
        Assert.assertEquals(statusCode,RESPONSE_STATUS_CODE_201,"stutus code is not 201");

        String responseString= EntityUtils.toString(closeableHttpResponse.getEntity());
        JSONObject responseJson=JSON.parseObject(responseString);

        String name= TestUtil.getValueByJPath(responseJson,"name");
        String job=TestUtil.getValueByJPath(responseJson,"job");
        Assert.assertEquals(name,"navy","name is not same");
        Assert.assertEquals(job,"tester","job is not same");

    }
}

​

      建議,在寫測試用例過程中,需要和postman上的請求結果參考,特別是Headers這裡的鍵值對。這裡留一個作業,上面我寫了一個Get帶請求頭的封裝方法,你可以對照postman中的請求頭去寫一個單元測試用例去測試下這個帶headers的Get方法。

       目前,Java介面自動化測試框架的核心部分,http請求方法的封裝已經完成。接下里還有測試日誌,測試報告,或者其他需要抽取優化的模組去完成。

參考博文:

https://blog.csdn.net/u011541946/article/details/80413667