httpclient+maven+excel+testng 框架实例----02 之代码详解

参考博客:https://blog.csdn.net/u011541946/article/category/7680864

 

1)TestBase.java 类:

package com.qa.base;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class TestBase{

public Properties properties;
// 定义常量: http响应状态码
public int RESPNSE_STATUS_CODE_200 = 200;
public int RESPNSE_STATUS_CODE_201 = 201;
public int RESPNSE_STATUS_CODE_404 = 404;
public int RESPNSE_STATUS_CODE_500 = 500;


public TestBase(){

try{
properties = new Properties();
FileInputStream fis = new FileInputStream(System.getProperty("user.dir")+"/src/main/java/com/qa/config/config.properties");
properties.load(fis);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e1){
e1.printStackTrace();
}
}
public static void main(String[] args){
TestBase testBase = new TestBase();
System.out.println(System.getProperty("user.dir"));
}
}


2)User.java类
package com.qa.data;

/**
* Created by jiangcui on 2018/6/4.
*/
public class User {
private String name;
private String job;

public User(){
super();
}

public User(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;
}
}


3)TestUtil类:
package com.qa.Util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
* Created by jiangcui on 2018/6/4.
*/
public class TestUtil {
/**

*

* @param responseJson ,这个变量是拿到响应字符串通过json转换成json对象

* @param jpath,这个jpath指的是用户想要查询json对象的值的路径写法

* jpath写法举例:1) per_page 2)data[1]/first_name ,data是一个json数组,[1]表示索引

* /first_name 表示data数组下某一个元素下的json对象的名称为first_name

* @return,返回first_name这个json对象名称对应的值

*/


//1 json解析方法

public static String getValueByJPath(JSONObject responseJson, String jpath){

Object obj = responseJson;

for(String s : jpath.split("/")) {

if(!s.isEmpty()) {

if(!(s.contains("[") || s.contains("]"))) {

obj = ((JSONObject) obj).get(s);

}else if(s.contains("[") || s.contains("]")) {

obj =((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("\\[")[1].replaceAll("]", "")));

}
}
}
return obj.toString();
}
}



4)RestClient.java类:
package com.qa.restclient;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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 org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

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

/**
* Created by jiangcui on 2018/6/4.
*/
public class RestClient {
final static Logger Log = Logger.getLogger(RestClient.class);

//1.不带请求头的get方法
public HttpResponse get(String url) throws ClientProtocolException, IOException {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

HttpGet httpGet = new HttpGet(url);
Log.info("开始发送get请求...");
HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
Log.info("发送请求成功,开始得到响应对象...");
return httpResponse;
}

//2.带请求头的get方法

public HttpResponse get(String url,HashMap<String,String> hashMap) throws ClientProtocolException, IOException {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

HttpGet httpGet = new HttpGet(url);
Log.info("开始发送带请求头的get请求...");

//加载请求头到httpGet对象
for(Map.Entry<String,String> entry:hashMap.entrySet()){
httpGet.addHeader(entry.getKey(),entry.getValue());
}

//执行请求代码
HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
Log.info("发送带请求头的get请求成功,开始得到响应对象...");
return httpResponse;
}

//3.post方法
public HttpResponse post(String url,String entityString,HashMap<String,String> hashMap)throws ClientProtocolException, IOException{
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(url);

//加载请求头到httpPost对象
for(Map.Entry<String,String> entry:hashMap.entrySet()){
httpPost.addHeader(entry.getKey(),entry.getValue());
}
//设置payload
httpPost.setEntity(new StringEntity(entityString,"utf-8"));

//执行请求
HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
Log.info("开始发送post请求");
return httpResponse;

}

//4.put方法,同post方法
public CloseableHttpResponse put(String url, String entityString, HashMap<String,String> headerMap) throws ClientProtocolException, IOException {

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPut httpput = new HttpPut(url);
httpput.setEntity(new StringEntity(entityString));

for(Map.Entry<String, String> entry : headerMap.entrySet()) {
httpput.addHeader(entry.getKey(), entry.getValue());
}
//发送put请求
CloseableHttpResponse httpResponse = httpclient.execute(httpput);
return httpResponse;
}

//5.delete方法
public CloseableHttpResponse delete(String url) throws ClientProtocolException, IOException {

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDelete httpdel = new HttpDelete(url);

//发送delete请求
CloseableHttpResponse httpResponse = httpclient.execute(httpdel);
return httpResponse;
}


//获取状态码
public int getHttpResponesCode(HttpResponse hr) {

int httpResponseCode = hr.getStatusLine().getStatusCode();
Log.info("解析得到响应状态码:"+ httpResponseCode);
// System.out.println("The httpResponseCode is "+ httpResponseCode);
return httpResponseCode;
}
//获取响应内容
public JSONObject getEntity(HttpResponse hr) throws IOException {
Log.info("得到响应对象的String格式");
String entity = EntityUtils.toString(hr.getEntity());

//将响应内容转换为JSON
JSONObject jsonObject = JSONObject.parseObject(entity);
// System.out.println("转化为Json格式为:" + jsonObject);
Log.info("返回响应内容的json格式:"+ jsonObject);
return jsonObject;
}

//获取响应头信息
public HashMap<String, String> getAllHeaders(HttpResponse hr) throws IOException {
Header[] headers = hr.getAllHeaders();
HashMap<String, String> hashMap = new HashMap<String, String>();
for (Header h : headers) {
hashMap.put(h.getName(), h.getValue());
}
// System.out.println("response headers:" + hashMap);
Log.info("get请求获取响应头信息...");
return hashMap;
}
}


5)GetApiTest.java测试类:
package com.qa.tests;

import com.alibaba.fastjson.JSONObject;
import com.qa.Util.TestUtil;
import com.qa.base.TestBase;
import com.qa.restclient.RestClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;


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

/**
* Created by jiangcui on 2018/6/4.
*/
public class GetApiTest extends TestBase {

TestBase testBase;
String host;
String url;
RestClient restClient;

final static Logger Log = Logger.getLogger(GetApiTest.class);


@BeforeClass
public void setup(){
testBase = new TestBase();
host = properties.getProperty("Host");
url = host+"/api/users";
}

@Test
public void getApiTest()throws ClientProtocolException,IOException {
Log.info("开始执行用例...");

restClient = new RestClient();
HttpResponse httpResponse = restClient.get(url);

Log.info("测试响应状态码是否是200...");
int httpResponesCode = restClient.getHttpResponesCode(httpResponse);
Assert.assertEquals(httpResponesCode,RESPNSE_STATUS_CODE_200,"response status code is not 200");

JSONObject jsonObject = restClient.getEntity(httpResponse);
System.out.println("转化为Json格式为:" + jsonObject);

HashMap<String, String> hm = restClient.getAllHeaders(httpResponse);
System.out.println("response headers:" + hm);


String s = TestUtil.getValueByJPath(jsonObject,"total");
Log.info("执行无路径JSON解析,解析的内容是 " + s);
System.out.println(s);
Assert.assertEquals(s,"12","total is not 12");
Log.info("接口内容响应断言1成功...");

String s1 = TestUtil.getValueByJPath(jsonObject,"data[0]/last_name");
Log.info("执行带路径JSON解析,解析的内容是 " + s1);
System.out.println(s1);

Assert.assertEquals(s1,"Bluth","last_name is not Bluth");
Log.info("接口内容响应断言2成功...");

Log.info("用例结束...");
}

}


6)PostApiTest.java类:

package com.qa.tests;

import com.alibaba.fastjson.JSONObject;
import com.qa.Util.TestUtil;
import com.qa.base.TestBase;
import com.qa.data.User;
import com.qa.restclient.RestClient;
import org.apache.http.HttpResponse;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

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

/**
* Created by jiangcui on 2018/6/4.
*/
public class PostApiTest extends TestBase {
TestBase testBase;
String host;
String url;
RestClient restClient;

final static Logger Log = Logger.getLogger(PostApiTest.class);


@BeforeClass
public void setup(){
testBase = new TestBase();
host = properties.getProperty("Host");
url = host+"/api/users";
}

// 静态方法,封装字符串转化为json字符串
public static String getJSONString(String name,String job){

Log.info("封装getJSONString方法...");

HashMap<String,String> hm = new HashMap<String, String>();
hm.put("name",name);
hm.put("job",job);
String userJsonString = JSONObject.toJSONString(hm);
System.out.println(userJsonString);
return userJsonString;
}

@DataProvider(name = "createData")
public Object[][] createData(){
Log.info("创建datapovider数据...");

return new Object[][]{
{"jiangcui01","manager"},
{"jiangcui02","devicer"},
{"jiangcui03","tester"}
};
}


//@Parameters({"Name","Job"})

@Test(dataProvider = "createData")
public void postApi(String name,String job) throws IOException {
Log.info(" 用例开始...");
restClient = new RestClient();

//1.采用@Parameters方法传值,提供pyload
//2.采用dataProvider传值,提供pyload
Log.info("准备pyload数据...");
String userJsonString = PostApiTest.getJSONString(name,job);

//2. 采用javabean传值,提供pyload
/*User user = new User("jiangcui","tester");
String userJsonString = JSONObject.toJSONString(user);
System.out.println(userJsonString);
*/

//准备请求头信息
Log.info("设置请求头信息...");
HashMap<String,String> hashMap = new HashMap<String, String>();
hashMap.put("Content-Type","application/json");

//执行post方法
HttpResponse httpResponse = restClient.post(url,userJsonString,hashMap);
Log.info("测试响应状态码是否是201...");
int httpResponesCode = restClient.getHttpResponesCode(httpResponse);
Assert.assertEquals(httpResponesCode,RESPNSE_STATUS_CODE_201,"response status code is not 200");

JSONObject jsonObject = restClient.getEntity(httpResponse);
System.out.println("转化为Json格式为:" + jsonObject);

//调用类TestUtil的静态方法

String s = TestUtil.getValueByJPath(jsonObject,"name");
if(!s.equals("")){
if(s.equals("jiangcui01")) {
Assert.assertEquals(s, "jiangcui01", "name is not jiangcui01");
}else if(s.equals("jiangcui02")){
Assert.assertEquals(s, "jiangcui02", "name is not jiangcui02");
}else{
Assert.assertEquals(s, "jiangcui03", "name is not jiangcui03");
}
}
Log.info("接口内容响应断言1成功...");

String s1 = TestUtil.getValueByJPath(jsonObject,"job");
if(!s1.equals("")){
if(s1.equals("manager")) {
Assert.assertEquals(s1, "manager", "name is not manager");
}else if(s1.equals("devicer")){
Assert.assertEquals(s1, "devicer", "name is not devicer");
}else{
Assert.assertEquals(s1, "tester", "name is not tester");
}
}
Log.info("接口内容响应断言2成功...");

Log.info("用例结束...");

}

}


 

posted on 2018-06-05 17:12  chenzx0918  阅读(692)  评论(0编辑  收藏  举报

导航