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 开始测试,结果如下所示:
————————————————
版权声明:本文为CSDN博主「东方欲晓-」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wd168/article/details/106884297