一.moco架構mock接口資訊
[
{
"description": "這是一個能傳回cookies資訊的get請求",
"request": {
"uri": "/getCookies",
"method": "get"
},
"response": {
"cookies": {
"login": "true"
},
"text": "成功擷取到cookies資訊啦"
}
}
]
二.application.properties配置檔案資訊
test.url=http://localhost:8080
getCookies.uri=/getCookies
三.編寫testNG測試方法
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Created with IntelliJ IDEA.
*
* @Auther: 目光定晴天
* @Date: 2021/6/5 11:14
* @Description:
*/
public class MyCookiesForGet {
private String url;
private ResourceBundle bundle;
//用來存儲cookies資訊的變量
private CookieStore cookieStore;
//在測試方法執行前加載配置檔案
@BeforeTest
public void beforeTest(){
//如何讀取配置檔案?---java.util.ResourceBundle,隻需要傳參為配置檔案的字首即可
bundle = ResourceBundle.getBundle("application", Locale.CHINA);
url = bundle.getString("test.url");
}
//舊版httpclient4.1.2
@Test
public void testGetCookies1() throws IOException {
//1.拼接組裝URL
String uri = bundle.getString("getCookies.uri");
String testUrl = this.url + uri;
//2.建立client對象(HttpClient無法擷取cookie,隻能通過DefaultHttpClient),get請求
HttpGet get = new HttpGet(testUrl);
DefaultHttpClient client = new DefaultHttpClient();
//3.執行get請求,獲得response對象
HttpResponse response = client.execute(get);
//4.獲得響應正文
String result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//5.獲得cookiestore并為此類的全局變量指派
this.cookieStore = client.getCookieStore();
//6.擷取cookie,并列印輸出
List<Cookie> cookieList = this.cookieStore.getCookies();
for (Cookie c:
cookieList) {
System.out.println("cookie name=" + c.getName() + ";cookie value=" + c.getValue());
}
}
//新版httpclient4.5.2
@Test
public void testGetCookies() throws IOException {
//從配置檔案拼接測試的URL
String uri;
String testUrl;
uri = bundle.getString("getCookies.uri");
testUrl = this.url + uri;
//擷取get方法
HttpGet get = new HttpGet(testUrl);
//建立cookiestore
CookieStore cookieStore = new BasicCookieStore();
//建立CloseableHttpClient對象,同時設定cookiestore
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//初始化response對象和正文響應字元串為null
CloseableHttpResponse response = null;
String result = null;
//執行get方法
try{
response = client.execute(get);
//為響應資料指定utf-8格式
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//擷取cookiestore,為全局變量cookieStore指派
this.cookieStore = cookieStore;
//列印輸出
List<Cookie> cookieList = this.cookieStore.getCookies();
for (Cookie c:
cookieList) {
System.out.println("cookie name=" + c.getName() + ";cookie value=" + c.getValue());
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
四.啟動服務,測試運作