1.首先配置好测试用的mock接口
[
{
"description":"这是一个带cookies信息的get请求",
"request":{
"uri":"/getcookies",
"method":"get"
},
"response":{
"cookies":{
"login":"true"
},
"text":"获得cookies信息成功"
}
},
{
"description":"这是一个带cookies信息的post请求",
"request":{
"uri":"/post/with/cookies",
"method":"post",
"cookies":{
"login":"true"
},
"json":{
"name":"lyn",
"age":"18"
}
},
"response":{
"status":200,
"json":{
"lyn":"lyn",
"code":"1"
}
}
}
]
我们要做的是从/getcookies接口中获取”login”:”true”的cookies信息,然后携带该信息去访问/post/with/cookies接口
2.全局变量配置url信息
resource目录下新建application.properties文件,文件内配置访问接口的url和路径
test.url=http://localhost:8899
test.getcookies.uri=/getcookies
test.post.with.cookies=/post/with/cookies
3.测试准备
从配置文件中读取url,以及准备储存cookies信息的变量
private String url;
private ResourceBundle bundle;
//用来存取cookies信息的变量
private CookieStore store;
@BeforeTest
public void beforeTest(){
bundle = ResourceBundle.getBundle("application",Locale.CHINA);
url = bundle.getString("test.url");
}
4.访问/getcookies接口以获取cookies信息
@Test
public void testGetCookies() throws IOException {
//从配置文件中,提取并拼接url
String uri = bundle.getString("test.getcookies.uri");
String testUrl = this.url+uri;
//获取body
String result;
HttpGet get = new HttpGet(testUrl);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//获取cookies信息
this.store = client.getCookieStore();
List<Cookie> cookieList = store.getCookies();
for (Cookie cookie : cookieList){
String name =cookie.getName();
String value = cookie.getValue();
System.out.println("访问/getcookies接口成功,cookie name = "+name+", cookie value = "+value);
}
}
5.携带由步骤4中获取的cookies信息访问/post/with/cookies接口
@Test(dependsOnMethods = {"testGetCookies"})
public void testPostCookies() throws IOException {
//从配置文件中,提取并拼接url
String uri = bundle.getString("test.post.with.cookies");
String testUrl = this.url+uri;
//声明一个Client对象,用来进行方法的执行
DefaultHttpClient client = new DefaultHttpClient();
//声明一个方法,这个方法就是post方法
HttpPost post = new HttpPost(testUrl);
//添加参数
JSONObject param = new JSONObject();
param.put("name","lyn");
param.put("age","18");
//设置header信息
post.setHeader("content-type","application/json");
//将参数信息添加到方法中
StringEntity entity = new StringEntity(param.toString(),"utf-8");
post.setEntity(entity);
//声明一个对象来进行相应结果的存储
String result;
//设置cookies信息
client.setCookieStore(this.store);
//执行post方法
HttpResponse response = client.execute(post);
//获取相应结果
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//将返回的相应结果字符串转化为json对象
JSONObject resultJson = new JSONObject(result);
//获取到结果值
String lyn = (String)resultJson.get("lyn");
String status = (String) resultJson.get("code");
//具体判断返回结果的值
Assert.assertEquals("lyn",lyn);
Assert.assertEquals("1",status);
}
查看结果