前情回顾
什么是接口测试
基于HTTP协议,通过工具或者代码模拟请求,检查响应结果是否符合接口说明文档的一种测试
接口测试分类
系统对外的接口
系统内部的接口
接口测试的意义
安全性、执行效率、介入时间、稳定性
HTTP协议的报文
请求报文:请求行(请求方式、网址、协议版本)、信息头、消息体
响应报文:状态行(协议版本、状态码、状态名称)、信息头、消息体
如何做接口测试
找开发要接口说明文档
根据文档,设计测试用例
编写代码实现接口测试
定期执行接口测试代码
检查生成的测试报告
编写测试总结报告
通过HttpClient模拟get请求的代码
1.创建HttpClient
CloseableHttpClient client = HttpClients.creatDefault();
2.构建网址
URI uri = new URIBuilder()
.setScheme("协议")
.setHost("域名")
.setPort(端口号)
.setPath("路径")
.setParameter("参数的键", "参数的值")
......
.build();
3.创建请求
HttpGet get = new HttpGet(uri);
4.执行请求,获取响应
CloseableHttpResponse response = client.execute(get);
5.检查响应结果
状态行
response.getStatusLine()
信息头
response.getAllHeaders()
消息体
response.getEntity()
练习
在众多接口中选择自己感兴趣的来试一试,编写接口代码
这里我以毒鸡汤为例
可以得到接口地址,请求方式等其他信息
代码如下
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class DuJiTang {
@Test
public void testJiTang() throws URISyntaxException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
//接口地址
//https://api.oick.cn/dutang/api.php
URI uri = new URIBuilder()
.setScheme("https")
.setHost("api.oick.cn")
//端口号可省略不写
//.setPort(443)
.setPath("dutang/api.php")
//没有需要输入的参数
//.setParameter()
.build();
HttpGet get = new HttpGet(uri);
CloseableHttpResponse response = client.execute(get);
System.out.println(response.getStatusLine());
Header[] headers = response.getAllHeaders();
for (Header h : headers){
System.out.println(h);
}
String responseText = EntityUtils.toString(response.getEntity());
System.out.println(responseText);
}
}
执行结果