前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >测试框架-TestNG-结合Selenium、Appium、OkHttp、HttpClient的简单示例

测试框架-TestNG-结合Selenium、Appium、OkHttp、HttpClient的简单示例

作者头像
wangmcn
发布2022-07-25 16:05:29
1.3K0
发布2022-07-25 16:05:29
举报
文章被收录于专栏:AllTests软件测试

结合Selenium、Appium、OkHttp、HttpClient的简单示例

目录

  • 1、TestNG+Selenium
  • 2、TestNG+Appium
  • 3、TestNG+OkHttp
  • 4、TestNG+HttpClient

1、TestNG+Selenium

创建My_TestNG_Selenium_Demo项目。

base包用于存放基础准备(BaseParpare类),即启动与退出。

testcases包用于存放测试用例(CaseDemo类)。

driver文件夹存放浏览器驱动(Chrome浏览器驱动)。

lib文件夹存放项目依赖的jar包(Selenium jar包)。

1、BaseParpare类(存放用例执行前与执行后的操作)

脚本代码:

代码语言:javascript
复制
package com.demo.base;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

public class BaseParpare {

       public WebDriver driver;

       @BeforeClass
       public void setUp() {
              System.setProperty("webdriver.chrome.driver", "D:\\workspace2\\My_TestNG_Selenium_Demo\\driver\\chromedriver.exe");
              ChromeOptions option = new ChromeOptions();
              option.addArguments("disable-infobars");
              driver = new ChromeDriver(option);
              driver.manage().window().maximize();
              driver.navigate().to("http://www.baidu.com");
       }

       @AfterClass
       public void tearDown() {
              driver.close();
              driver.quit();
       }
      
}

2、CaseDemo类(继承BaseParpare类,存放用例)

脚本代码:

代码语言:javascript
复制
package com.demo.testcases;

import org.openqa.selenium.By;
import org.testng.annotations.Test;

import com.demo.base.BaseParpare;

public class CaseDemo extends BaseParpare {

       @Test
       public void testCase1() {
              driver.findElement(By.id("kw")).sendKeys("selenium");
       }

       @Test
       public void testCase2() {
              driver.findElement(By.id("su")).click();
       }

       @Test
       public void testCase3() {
              System.out.println(driver.getTitle());
       }

}

3、testng.xml

文件内容:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" thread-count="1">
 
       <test name="Test" enabled="true">
              <classes>
                     <class name="com.demo.testcases.CaseDemo" />
              </classes>
       </test>
 
</suite>

4、执行脚本(testng.xml鼠标右键Run As--->TestNG Suite)。

5、执行结果:

控制台打印结果信息:3个测试方法执行成功。

TestNG结果报告:

2、TestNG+Appium

创建My_TestNG_Appium_Demo项目。

base包用于存放基础准备(BaseParpare类),即启动与退出。

testcases包用于存放测试用例(CaseDemo类)。

app文件夹存放测试应用(testApp.apk)。

lib文件夹存放项目依赖的jar包(Appium jar包、Selenium jar包)。

1、BaseParpare类(存放用例执行前与执行后的操作)

脚本代码:

代码语言:javascript
复制
package com.demo.base;

import java.io.File;
import java.net.URL;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;

public class BaseParpare {

       public AndroidDriverdriver;

       @BeforeClass
       public void setUp() throws Exception {

              File classpathRoot = new File(System.getProperty("user.dir"));
              File appDir = new File(classpathRoot, "app");
              File app = new File(appDir, "testApp.apk");

              DesiredCapabilities capabilities = new DesiredCapabilities();

              // 使用哪个自动化测试引擎
              // 默认为Appium,或Selendroid或UiAutomator2或Espresso用于Android;或XCUITest用于IOS
              capabilities.setCapability("automationName", "Appium");

              // 使用哪个移动操作系统平台
              // iOS, Android, FirefoxOS
              capabilities.setCapability("platformName", "Android");

              // 移动操作系统版本
              capabilities.setCapability("platformVersion", "6.0");

              // 使用的移动设备或模拟器的类型
              // iPhone Simulator, iPad Simulator, iPhone Retina 4-inch, Android
              // Emulator, Galaxy S4 等等
              // 在IOS上,这个关键字的值必须是使用`instruments -s devices`得到的可使用的设备名称之一
              // 在Android上,这个关键字目前不起作用
              capabilities.setCapability("deviceName", "honor");

              // 连接的物理设备的唯一设备标识
              capabilities.setCapability("udid", "MYV0215825000026");

              // `.ipa`或`.apk`文件所在的本地绝对路径或者远程路径,也可以是一个包括两者之一的`.zip`
              // Appium会先尝试安装路径对应的应用在适当的真机或模拟器上
              // 针对Android,如果你指定`app-package`和`app-activity`的话,那么就可以不指定`app`
              // 例如/abs/path/to/my.apk or http://myapp.com/app.ipa
              capabilities.setCapability("app", app.getAbsolutePath());

              // 要运行Android应用的包名
              capabilities.setCapability("appPackage", "com.example.testapp");

              // 要从包中启动的Android activity的活动名称
              capabilities.setCapability("appActivity", "com.example.testapp.MainActivity");

              // 启用Unicode输入法,设置为true可以输入中文字符,默认为false
              capabilities.setCapability("unicodeKeyboard", true);

              // 在设定了`unicodeKeyboard`关键字运行Unicode测试结束后,将键盘重置为其原始状态
              // 如果单独使用,将会被忽略,默认值`false`
              capabilities.setCapability("resetKeyboard", true);

              // 设置为true,每次启动时覆盖session,否则第二次运行会报错不能新建session
              capabilities.setCapability("sessionOverride", true);

              // 在此会话之前不要重置应用程序状态
              // Android 不要停止应用程序,不要清除应用程序数据,也不要卸载apk
              // IOS 测试后不要销毁或关闭SIM卡。开始测试运行在任何模拟运行,或设备插入
              capabilities.setCapability("noReset", true);

              // 执行完整的重置
              // Android 停止应用程序,清除应用程序数据并在测试后卸载apk
              // IOS 在真机设备测试后卸载应用程序,在模拟器测试后摧毁模拟器
              capabilities.setCapability("fullReset", false);

              // 设置命令超时时间,单位:秒
              // 达到超时时间仍未接收到新的命令时Appium会假设客户端退出然后自动结束会话
              capabilities.setCapability("newCommandTimeout", 60);

              driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
              Thread.sleep(2000);
       }

       @AfterClass
       public void tearDown() {
              driver.quit();
       }
      
}

2、CaseDemo类(继承BaseParpare类,存放用例)

脚本代码:

代码语言:javascript
复制
package com.demo.testcases;

import org.openqa.selenium.By;
import org.testng.annotations.Test;

import com.demo.base.BaseParpare;

public class CaseDemo extends BaseParpare {

       @Test
       public void testCase1() {
              driver.findElement(By.id("com.example.testapp:id/urlField")).sendKeys("https://www.baidu.com/");
       }

       @Test
       public void testCase2() {
              driver.findElement(By.id("com.example.testapp:id/goButton")).click();
       }

}

3、testng.xml

文件内容:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" thread-count="1">
 
       <test name="Test" enabled="true">
              <classes>
                     <class name="com.demo.testcases.CaseDemo" />
              </classes>
       </test>
 
</suite>

4、开启Appium服务,执行脚本(testng.xml鼠标右键Run As--->TestNG Suite)。

5、执行结果:

控制台打印结果信息:2个测试方法执行成功。

TestNG结果报告:

3、TestNG+OkHttp

本小节接口请求链接使用moco生成。

如图所示:需要用到moco包和Json配置文件(已经配置完成)。

启动moco服务:

命令行进入moco包所在目录。

输入 java -jar moco-runner-0.12.0-standalone.jar http -p 8083 -c mymoco.json

如图所示:moco服务开启,就可以使用接口请求链接了。

创建My_TestNG_OkHttp_Demo项目。

Get类(Get请求)。

Post类(Post请求)。

application.properties文件(配置文件,设置请求链接)。

lib文件夹存放项目依赖的jar包(OkHttp包、Json包)。

1、Get类。

getCookie方法:使用Get请求,获取响应的Cookie信息。

getWithCookie方法:依赖getCookie方法,使用Get请求,将getCookie方法获取的Cookie信息做为请求头Cookie。

脚本代码:

代码语言:javascript
复制
package com.test.demo;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;

import org.testng.annotations.Test;

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Get请求
 *
 * @author wangmcn
 *
 */
public class Get {
      
       final int CONNECT_TIMEOUT = 30;
       final int READ_TIMEOUT = 30;
       final int WRITE_TIMEOUT = 30;
      
       // 创建OkHttpClient对象
       OkHttpClient client = new OkHttpClient.Builder()
                     .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置连接超时时间
                     .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // 设置读超时时间
                     .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // 设置写超时时间
                     .retryOnConnectionFailure(true) // 是否自动重连
                     .build();

       private String store;
       private static String url;
       private static ResourceBundle rb;
       private static BufferedInputStream inputStream;
      
       static {
              String proFilePath = System.getProperty("user.dir") + "\\config\\application.properties";
              try {
                     inputStream = new BufferedInputStream(new FileInputStream(proFilePath));
                     rb = new PropertyResourceBundle(inputStream);
                     url = rb.getString("url");
                     inputStream.close();
              } catch (FileNotFoundException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
       }

       @Test
       public void getCookie() throws IOException {

              // 从配置文件中拼接测试的url
              String uri = rb.getString("getCookie.uri");
              String testUrl = url + uri;

              // 创建Request对象
              Request request = new Request.Builder()
                            .url(testUrl)
                            .get()
                            .build();
             
              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
                     System.out.println("获取网页源码: " + response.body().string());
              }
             
              // 获取响应头
              Headers responseHeader = response.headers();
              System.out.println("获取响应头: " + responseHeader);
             
              // 获取Cookie
              this.store = responseHeader.get("Set-Cookie");
              System.out.println("获取Cookie: " + responseHeader.get("Set-Cookie"));
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();
             
       }

       @Test(dependsOnMethods = { "getCookie" })
       public void getWithCookie() throws IOException {
             
              // 从配置文件中拼接测试的url
              String uri = rb.getString("get.cookie");
              String testUrl = url + uri;

              // 创建Request对象
              Request request = new Request.Builder()
                            .url(testUrl)
                            .addHeader("Cookie", this.store)
                            .get()
                            .build();
             
              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
                     System.out.println("获取网页源码: " + response.body().string());
              }
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();

       }

}

2、Post类。

getCookie方法:使用Get请求,获取响应的Cookie信息。

postWithCookie方法:依赖getCookie方法,使用Post请求,将getCookie方法获取的Cookie信息做为请求头Cookie,发送Json数据。

脚本代码:

代码语言:javascript
复制
package com.test.demo;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Post请求
 *
 * @author wangmcn
 *
 */
public class Post {

       final int CONNECT_TIMEOUT = 30;
       final int READ_TIMEOUT = 30;
       final int WRITE_TIMEOUT = 30;
      
       // 创建OkHttpClient对象
       OkHttpClient client = new OkHttpClient.Builder()
                     .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置连接超时时间
                     .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // 设置读超时时间
                     .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // 设置写超时时间
                     .retryOnConnectionFailure(true) // 是否自动重连
                     .build();

       private String store;
       private static String url;
       private static ResourceBundle rb;
       private static BufferedInputStream inputStream;
      
       static {
              String proFilePath = System.getProperty("user.dir") + "\\config\\application.properties";
              try {
                     inputStream = new BufferedInputStream(new FileInputStream(proFilePath));
                     rb = new PropertyResourceBundle(inputStream);
                     url = rb.getString("url");
                     inputStream.close();
              } catch (FileNotFoundException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
       }

       @Test
       public void getCookie() throws IOException {

              // 从配置文件中拼接测试的url
              String uri = rb.getString("getCookie.uri");
              String testUrl = url + uri;

              // 创建Request对象
              Request request = new Request.Builder()
                            .url(testUrl)
                            .get()
                            .build();
             
              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
                     System.out.println("获取网页源码: " + response.body().string());
              }
             
              // 获取响应头
              Headers responseHeader = response.headers();
              System.out.println("获取响应头: " + responseHeader);
             
              // 获取Cookie
              this.store = responseHeader.get("Set-Cookie");
              System.out.println("获取Cookie: " + responseHeader.get("Set-Cookie"));
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();
             
       }

       @Test(dependsOnMethods = { "getCookie" })
       public void postWithCookie() throws IOException {
             
              // 从配置文件中拼接测试的url
              String uri = rb.getString("post.cookie");
              String testUrl = url + uri;

              // 数据类型为Json格式
              MediaType JSON = MediaType.parse("application/json; charset=utf-8");
              // Json数据
              String jsonStr = "{\"username\":\"admin\",\"password\":\"123456\"}";
              // 得到RequestBody对象
              RequestBody body = RequestBody.create(JSON, jsonStr);
             
              // 创建Request对象
              Request request = new Request.Builder()
                            .url(testUrl)
                            .addHeader("Content-Type", "application/json;charset:utf-8")
                            .addHeader("Cookie", this.store)
                            .post(body)
                            .build();

              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
              }
             
              // 将返回的响应结果字符串转化成为Json对象
              JSONObject resultJson = new JSONObject(response.body().string());
              System.out.println("获取网页源码: " + resultJson);
             
              // 断言
              Assert.assertEquals((String)resultJson.get("admin"), "success");
              Assert.assertEquals((String)resultJson.get("status"), "1");
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();
             
       }

}

3、testng.xml

文件内容:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" thread-count="1">
 
       <test name="Test" enabled="true">
              <classes>
                     <class name="com.test.demo.Get" />
                     <class name="com.test.demo.Post" />
              </classes>
       </test>
 
</suite>

4、执行脚本(testng.xml鼠标右键Run As--->TestNG Suite)。

5、执行结果:

控制台打印结果信息:4个测试方法执行成功。

4、TestNG+HttpClient

本小节接口请求链接使用moco生成。

如图所示:需要用到moco包和Json配置文件(已经配置完成)。

启动moco服务:

命令行进入moco包所在目录。

输入 java -jar moco-runner-0.12.0-standalone.jar http -p 8083 -c mymoco.json

如图所示:moco服务开启,就可以使用接口请求链接了。

创建My_TestNG_HttpClient_Demo项目。

Get类(Get请求)。

Post类(Post请求)。

application.properties文件(配置文件,设置请求链接)。

lib文件夹存放项目依赖的jar包(HttpClient包、Json包)。

1、Get类。

getCookie方法:使用Get请求,获取响应的Cookie信息。

getWithCookie方法:依赖getCookie方法,使用Get请求,将getCookie方法获取的Cookie信息做为请求头Cookie。

脚本代码:

代码语言:javascript
复制
package com.test.demo;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;

/**
 * Get请求
 *
 * @author wangmcn
 *
 */
public class Get {

       private Liststore;
       private CookieStore cookieStore;
       private static String url;
       private static ResourceBundle rb;
       private static BufferedInputStream inputStream;
      
       static {
              String proFilePath = System.getProperty("user.dir") + "\\config\\application.properties";
              try {
                     inputStream = new BufferedInputStream(new FileInputStream(proFilePath));
                     rb = new PropertyResourceBundle(inputStream);
                     url = rb.getString("url");
                     inputStream.close();
              } catch (FileNotFoundException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
       }

       @Test
       public void getCookie() throws ClientProtocolException, IOException {

              // 从配置文件中拼接测试的url
              String uri = rb.getString("getCookie.uri");
              String testUrl = url + uri;

              // 创建CookieStore对象
           cookieStore = new BasicCookieStore();
             
              // 创建CloseableHttpClient对象
              CloseableHttpClient httpclient = HttpClients.custom()
                            // 设置Cookie
                            .setDefaultCookieStore(cookieStore)
                            .build();
             
              // 创建HttpGet对象
              HttpGet httpget = new HttpGet(testUrl);

              // 设置超时
              RequestConfig requestConfig = RequestConfig.custom()
                            .setConnectTimeout(15000) // 设置连接超时时间,单位毫秒
                            .setSocketTimeout(15000) // 请求获取数据的超时时间,单位毫秒
                            .setConnectionRequestTimeout(15000) // 设置从connect Manager获取Connection超时时间,单位毫秒
                            .build();
              httpget.setConfig(requestConfig);
             
              // 执行Get请求
              CloseableHttpResponse response = httpclient.execute(httpget);
              // 获取响应状态
              System.out.println("获取响应状态: " + response.getStatusLine().getStatusCode());
              // 获取返回实体
              HttpEntity entity = response.getEntity();
              // 获取网页源码
              System.out.println("获取网页源码:" + EntityUtils.toString(entity, "utf-8"));
              // 获取响应内容类型
              System.out.println("获取响应内容类型:" + entity.getContentType().getValue());
             
              // 获取Cookie
              this.store = cookieStore.getCookies();
              ListcookieList = cookieStore.getCookies();
              for (Cookie cookies : cookieList) {
                     System.out.println("Cookie: " + cookies.getName() + "; " + cookies.getValue());
              }
             
              // 关闭流和释放系统资源
              response.close();
              // 关闭客户端
              httpclient.close();
      
       }

       @Test(dependsOnMethods = { "getCookie" })
       public void getWithCookie() throws ClientProtocolException, IOException {
             
              // 从配置文件中拼接测试的url
              String uri = rb.getString("get.cookie");
              String testUrl = url + uri;

              for (int i = 0; i < this.store.size(); i++) {
                     // 创建CookieStore对象
                     cookieStore = new BasicCookieStore();
                    
                     // 创建BasicClientCookie对象,添加Cookie
                     BasicClientCookie cookie = new BasicClientCookie(this.store.get(i).getName(), this.store.get(i).getValue());
                     cookie.setVersion(0);
                     cookie.setDomain("localhost");
                     cookie.setPath("/");
                     cookieStore.addCookie(cookie); 
              }

              // 创建CloseableHttpClient对象
              CloseableHttpClient httpclient = HttpClients.custom()
                            // 设置Cookie
                            .setDefaultCookieStore(cookieStore)
                            .build();
             
              // 创建HttpGet对象
              HttpGet httpget = new HttpGet(testUrl);

              // 设置超时
              RequestConfig requestConfig = RequestConfig.custom()
                            .setConnectTimeout(15000) // 设置连接超时时间,单位毫秒
                            .setSocketTimeout(15000) // 请求获取数据的超时时间,单位毫秒
                            .setConnectionRequestTimeout(15000) // 设置从connect Manager获取Connection超时时间,单位毫秒
                            .build();
              httpget.setConfig(requestConfig);
             
              // 执行Get请求
              CloseableHttpResponse response = httpclient.execute(httpget);

              // 获取响应状态
              int statusCode = response.getStatusLine().getStatusCode();
              System.out.println("获取响应状态: " + statusCode);

              if (statusCode == 200) {
                     String result = EntityUtils.toString(response.getEntity(), "utf-8");
                     System.out.println("获取网页源码:" + result);
              }

              // 关闭流和释放系统资源
              response.close();
              // 关闭客户端
              httpclient.close();
             
       }
}

2、Post类。

getCookie方法:使用Get请求,获取响应的Cookie信息。

postWithCookie方法:依赖getCookie方法,使用Post请求,将getCookie方法获取的Cookie信息做为请求头Cookie,发送Json数据。

脚本代码:

代码语言:javascript
复制
package com.test.demo;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;

/**
 * Post请求
 *
 * @author wangmcn
 *
 */
public class Post {

       private Liststore;
       private CookieStore cookieStore;
       private static String url;
       private static ResourceBundle rb;
       private static BufferedInputStream inputStream;
      
       static {
              String proFilePath = System.getProperty("user.dir") + "\\config\\application.properties";
              try {
                     inputStream = new BufferedInputStream(new FileInputStream(proFilePath));
                     rb = new PropertyResourceBundle(inputStream);
                     url = rb.getString("url");
                     inputStream.close();
              } catch (FileNotFoundException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
       }

       @Test
       public void getCookie() throws ClientProtocolException, IOException {

              // 从配置文件中拼接测试的url
              String uri = rb.getString("getCookie.uri");
              String testUrl = url + uri;

              // 创建CookieStore对象
           cookieStore = new BasicCookieStore();
             
              // 创建CloseableHttpClient对象
              CloseableHttpClient httpclient = HttpClients.custom()
                            // 设置Cookie
                            .setDefaultCookieStore(cookieStore)
                            .build();
             
              // 创建HttpGet对象
              HttpGet httpget = new HttpGet(testUrl);

              // 设置超时
              RequestConfig requestConfig = RequestConfig.custom()
                            .setConnectTimeout(15000) // 设置连接超时时间,单位毫秒
                            .setSocketTimeout(15000) // 请求获取数据的超时时间,单位毫秒
                            .setConnectionRequestTimeout(15000) // 设置从connect Manager获取Connection超时时间,单位毫秒
                            .build();
              httpget.setConfig(requestConfig);
             
              // 执行Get请求
              CloseableHttpResponse response = httpclient.execute(httpget);
              // 获取响应状态
              System.out.println("获取响应状态: " + response.getStatusLine().getStatusCode());
              // 获取返回实体
              HttpEntity entity = response.getEntity();
              // 获取网页源码
              System.out.println("获取网页源码:" + EntityUtils.toString(entity, "utf-8"));
              // 获取响应内容类型
              System.out.println("获取响应内容类型:" + entity.getContentType().getValue());
             
              // 获取Cookie
              this.store = cookieStore.getCookies();
              ListcookieList = cookieStore.getCookies();
              for (Cookie cookies : cookieList) {
                     System.out.println("Cookie: " + cookies.getName() + "; " + cookies.getValue());
              }
             
              // 关闭流和释放系统资源
              response.close();
              // 关闭客户端
              httpclient.close();
      
       }

       @Test(dependsOnMethods = { "getCookie" })
       public void postWithCookie() throws IOException {

              // 从配置文件中拼接测试的url
              String uri = rb.getString("post.cookie");
              String testUrl = url + uri;

              for (int i = 0; i < this.store.size(); i++) {
                     // 创建CookieStore对象
                     cookieStore = new BasicCookieStore();
                    
                     // 创建BasicClientCookie对象,添加Cookie
                     BasicClientCookie cookie = new BasicClientCookie(this.store.get(i).getName(), this.store.get(i).getValue());
                     cookie.setVersion(0);
                     cookie.setDomain("localhost");
                     cookie.setPath("/");
                     cookieStore.addCookie(cookie); 
              }

              // 创建CloseableHttpClient对象
              CloseableHttpClient httpclient = HttpClients.custom()
                            // 设置Cookie
                            .setDefaultCookieStore(cookieStore)
                            .build();

              // 创建HttpPost对象
              HttpPost httpPost = new HttpPost(testUrl);

              // 设置超时
              RequestConfig requestConfig = RequestConfig.custom()
                            .setConnectTimeout(15000) // 设置连接超时时间,单位毫秒
                            .setSocketTimeout(15000) // 请求获取数据的超时时间,单位毫秒
                            .setConnectionRequestTimeout(15000) // 设置从connect Manager获取Connection超时时间,单位毫秒
                            .build();
              httpPost.setConfig(requestConfig);
             
              // 设置请求头信息
              httpPost.setHeader("content-type", "application/json; charset=utf-8");
              // 添加Json参数
              JSONObject param = new JSONObject();
              param.put("username", "admin");
              param.put("password", "123456");
              // 将参数信息添加到方法中
              StringEntity entity = new StringEntity(param.toString(), "utf-8");
              httpPost.setEntity(entity);
             
              // 执行Post请求
              CloseableHttpResponse response = httpclient.execute(httpPost);
             
              // 获取响应结果
              String result = EntityUtils.toString(response.getEntity(), "utf-8");
             
              // 将返回的响应结果字符串转化成为Json对象
              JSONObject resultJson = new JSONObject(result);
              // 获取网页源码
              System.out.println("获取网页源码:" + resultJson);
             
              // 断言
              Assert.assertEquals((String)resultJson.get("admin"), "success");
              Assert.assertEquals((String)resultJson.get("status"), "1");
             
              // 关闭流和释放系统资源
              response.close();
              // 关闭客户端
              httpclient.close();

       }
      
}

3、testng.xml

文件内容:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" thread-count="1">
 
       <test name="Test" enabled="true">
              <classes>
                     <class name="com.test.demo.Get" />
                     <class name="com.test.demo.Post" />
              </classes>
       </test>
 
</suite>

4、执行脚本(testng.xml鼠标右键Run As--->TestNG Suite)。

5、执行结果:

控制台打印结果信息:4个测试方法执行成功。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-03-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AllTests软件测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 目录
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档