【自动化测试】HttpClient 模拟用户登录与请求接口完成自动化测试
来源:互联网 发布:c语言中的ifdef ifndef 编辑:程序博客网 时间:2024/06/06 01:14
在测试过程中,有时候需要传递大量的参数来验证接口有没有问题,公司一个项目用的SSH框架,测试框架用StrutSpringTestCase,但是在使用StrutSpringTestCase 框架我遇到个问题,在一个test case里面多次调用excecuteAction(url),虽然值传到了后台,但是结果永远只显示第一次请求的结果,通过查看源码问题出现在response上面,暂时我这边没有解决方案。这不利于我们测试,增加了我们写代码的工作量。我打算换个思路来做这件事情。
我想到了移动app请求 先有token,之后才能处理网络交互,于是我打算先登录,然后调用各个链接,这里面就需要session 的保存与传递了,如果session不传递,接口很容易调用失败,有时候还需要在session里面添加东西,刚开始我这边使用HttpUrlContection来解决,但是苦于不好处理session传递,只好放弃,之后转战用HttpClient,通过httpclient 可以实现 session的传递,大量参数来验证接口问题,同时,扩展一下,也可以用于一些登录网站的爬虫,最终的代码调用方式如下:
public class DemoTest {
String baseURL = "http://xxx.xxx.xxx.xxx:8888/web";
String actionUrl = baseURL + "xxx.action";
String AGTNUM = "xxx";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Main.Login();//模拟登录过程
}
/**
* 单独测试一个链接
*/
@Test
public void testGetById(){
try {
StringBuffer sql = new StringBuffer();
sql.append(" select xxx " );
List<Map<String, String>> sqlRet = DBUtil.selectDate(sql.toString(), null);
if (sqlRet != null && sqlRet.size() > 0) {
Map<String, String> firstRet = sqlRet.get(0);
String F_ID = firstRet.get("U_ID");
TestBean bean = Constant.getConstantList(F_ID, null);//一个集合常量
List<String> constantList = bean.getConstantList();
List<String> assertList = bean.getAssertList();
for(int i = 0;i<constantList.size();i++){
ZHttpClient.addCookie("key1", "value1","ip","path");//添加cookie过程
ZHttpClient.addCookie("key2", "value2","ip","path");//添加cookie过程
Map<String, String> paramd = new HashMap<String, String>();
paramd.put("relationId", constantList.get(i));
String rest = ZHttpClient.doPost(actionUrl, paramd);
JSONObject rets = JSONObject.fromObject(rest);
System.out.println(constantList.get(i)+"-->"+ rets);
assertEquals(assertList.get(i), rets.get("resultCode"));
rest = "";
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
登录代码没什么好说的,传递几个参数 然后调用 ZHttpClient.doPost(actionUrl, paramd);
这里面主要看ZHttpClient.doPost(actionUrl, paramd)做了什么事情:
public class ZHttpClient {
private static final Logger LOG = LogManager.getLogger(ZHttpClient.class);
public static CloseableHttpClient httpClient = null;
public static HttpClientContext context = null;
public static CookieStore cookieStore = null;
public static RequestConfig requestConfig = null;
private static String CHARSET = "utf-8";
static {
init();
}
private static void init() {
context = HttpClientContext.create();
cookieStore = new BasicCookieStore();
// 配置超时时间
requestConfig = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000)
.setConnectionRequestTimeout(60000).build();
// 设置默认跳转以及存储cookie
httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore).build();
}
/**
* post请求
* @param url
* @param param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public synchronized static String doPost(String url, Map<String, String> param ) throws ClientProtocolException, IOException{
HttpPost httpPost = new HttpPost(url);
String result = "";
try {
if (null != param && param.size() > 0) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Entry<String, String>> iterator = param.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, CHARSET);
httpPost.setEntity(entity);
}
}
CloseableHttpResponse response = httpClient.execute(httpPost, context);
result = getResponse(response);
cookieStore = context.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源 注意这个地方 根据业务需求而定
/*try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}*/
}
return result;
}
/**
* 手动增加cookie
* @param name
* @param value
* @param domain
* @param path
*/
public static void addCookie(String name, String value, String domain, String path) {
BasicClientCookie cookie = new BasicClientCookie(name, value);
cookie.setDomain(domain);
cookie.setPath(path);
cookieStore.addCookie(cookie);
}
/**
* 直接把Response内的Entity内容转换成String
*
* @param httpResponse
* @return
* @throws ParseException
* @throws IOException
*/
public static String getResponse(CloseableHttpResponse httpResponse) throws ParseException, IOException {
String ret = "";
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
ret = EntityUtils.toString(entity);
}
}
return ret;
}
}
通过以上代码就完成了 session的传递过程。
原创团队
【总监】十二春秋之,3483099@qq.com;
【Master】zelo,616701261@qq.com;【运营】狼行天下,897221533@qq.com;
【产品设计】流浪猫,364994559@qq.com;【体验设计】兜兜,2435632247@qq.com;
【iOS】淘码小工,492395860@qq.com;iMcG33K,imcg33k@gmail.com;
【Android】人猿居士,1059604515@qq.com;思路的顿悟,1217022114@qq.com;
【java】首席工程师MR_W,feixue300@qq.com;【测试】土镜问道,847071279@qq.com;
- 【自动化测试】HttpClient 模拟用户登录与请求接口完成自动化测试
- Excel+Httpclient,数据驱动接口自动化测试
- UI自动化测试,模拟用户操作。
- Instrumentation 自动化测试,模拟用户操作
- 接口自动化测试之http请求实践
- robot framework接口自动化测试post请求
- Url接口测试:HttpClient模拟登录效果
- 【接口测试】接口自动化测试
- 自动化测试数据模拟测试
- 接口自动化测试
- 接口自动化测试初探
- 接口自动化测试
- 接口自动化测试框架
- SoapUI接口自动化测试
- http接口自动化测试
- 接口自动化测试第一步
- postman接口自动化测试
- 接口自动化测试框架
- 范围内寻找素数组合、它们的和也为素数
- Questionnaire
- 移动web开发之DPR
- 神经网络-感知器算法python代码实现
- 记录week1
- 【自动化测试】HttpClient 模拟用户登录与请求接口完成自动化测试
- poj 1182 并查集经典
- Linux的学习笔记05:编写shell script
- ACM_博弈入门
- 栈的压入、弹出序列
- 一个兼容性强的错误日志预警机制
- 使用MyBatis-generator 自动生成MyBatis代码
- 前端面试之事件捕获、时间冒泡总结
- 2017多校联合第五场1006/hdu6090Rikka with Graph(思维公式)