7.1 引入 TestNG
上一章中我們還沒有很好的手段來執行測試和驗證結果,這裏我們引入 TestNG 來幫助完成這部分功能。
7.1.1 創建 TestNG 測試類
在項目目錄 src/test/java 下的包 com.mytest.httpclient.test 下新建一個支持testNG 的類,類名爲 testGet。
寫入以下測試代碼:
package com.mytest.httpclient.test;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.mytest.httpclient.Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class GetTest {
CloseableHttpClient client;
CloseableHttpResponse response;
HttpEntity responseBody;
int responseCode;
@BeforeTest
public void setUp() {
// 創建一個httpClient的實例
client = HttpClients.createDefault();
}
@Test
public void getTest() throws ClientProtocolException, IOException {
String url = "https://reqres.in/api/users?pages=2";
// 創建一個httpGet請求實例
HttpGet httpGet = new HttpGet(url);
// 使用httpClient實例發送剛創建的get請求,並用httpResponse將響應接收
response = client.execute(httpGet);
// 從響應中提取出狀態碼
responseCode = response.getStatusLine().getStatusCode();
Assert.assertEquals(responseCode, 200, "The response code should be 200!");
// 從響應中提取出響應主體
responseBody = response.getEntity();
//轉爲字符串
String responseBodyString = EntityUtils.toString(responseBody,"utf-8");
// 創建Json對象,把上面字符串序列化成Json對象
JSONObject responseJson = JSON.parseObject(responseBodyString);
// json內容解析
int page = responseJson.getInteger("page"); Assert.assertEquals(page, 2, "The
page value should be 2!");
String firstName = Util.getValueByJPath(responseJson, "data[0]/first_name");
Assert.assertEquals(firstName, "Michael", "The first name should be Michael!");
}
}
這裏我們在 beforeTest 裏去創建一個 HttpClient 的實例,beforeTest 方法是 TestNG 內置的方法,它會在測試方法執行之前被執行,所以可以在該方法中寫入一些初始化的代碼,然後在 getTest 方法中調用上一章中封裝好的方法獲取響應主體和狀態碼。
最後通過 Util 去獲取響應中的 first_name 信息,做爲核心驗證點。
在 getTest 方法裏我們使用 Assert.assertEquals 方法做了兩個斷言:
1. 判斷狀態碼是否正確;
2. 判斷 first_name 是否正確。
7.1.2 執行測試並查看結果
可以選中該類,右鍵點擊 Run As 中的 TestNG Test 開始測試,結果如下所示: