catalogue
-
1,Maven+Selenium
-
2,Maven+Appium
-
3,Maven+OkHttp
-
4,Maven+HttpClient
1,Maven+Selenium
Selenium+TestNG+Maven
Create My_Maven_Selenium_Demo project
The base package is used to store the basic preparation (basepare class), that is, start and exit.
The testcases package is used to store test cases (CaseDemo class).
The driver folder stores browser drivers (Chrome browser drivers).
1. Basepare class (stores the operations before and after the execution of the use case)
Script code:
package com.test.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(); } }
Here I recommend a software testing exchange group created by myself, QQ: 642830685. The group will share software testing resources, testing interview questions and testing industry information from time to time. You can actively exchange technology in the group, and big guys can answer questions and solve problems for you.
2. CaseDemo class (inheriting basepare class and storing use cases)
Script code:
package com.test.demo.testcases; import org.openqa.selenium.By; import org.testng.annotations.Test; import com.test.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
Document content:
<?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.testcases.CaseDemo" /> </classes> </test> </suite>
4,pom.xml
Added dependencies (TestNG, Selenium):
<dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.12.0</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-server</artifactId> <version>3.12.0</version> </dependency> </dependencies>
5. Execute the script (pom.xml. Right click Run as - > Maven test).
6. Execution result: console print result information: three test methods were executed successfully.
2,Maven+Appium
Appium+TestNG+Maven
Create My_Maven_Appium_Demo project
The base package is used to store the basic preparation (basepare class), that is, start and exit.
The testcases package is used to store test cases (CaseDemo class).
The app folder stores the test application (testApp.apk).
1. Basepare class (stores the operations before and after the execution of the use case)
Script code:
package com.test.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(); // Which automated test engine to use // The default is Appium, or Selendroid, UiAutomator2 or Espresso for Android; Or XCUITest for IOS capabilities.setCapability("automationName", "Appium"); // Which mobile operating system platform do you use // iOS, Android, FirefoxOS capabilities.setCapability("platformName", "Android"); // Mobile operating system version capabilities.setCapability("platformVersion", "6.0"); // Type of mobile device or emulator used // iPhone Simulator, iPad Simulator, iPhone Retina 4-inch, Android // Emulator, Galaxy S4, etc // On IOS, the value of this keyword must be one of the available device names obtained by using 'instruments -s devices' // On Android, this keyword does not work at present capabilities.setCapability("deviceName", "honor"); // Unique device ID of the connected physical device capabilities.setCapability("udid", "316d9073"); // `. ipa ` or ` The local absolute path or remote path where the apk file is located, or one including both zip` // Appium will first try to install the application corresponding to the path on the appropriate real machine or simulator // For Android, if you specify 'app package' and 'app activity', you can not specify 'app'` // For example, / ABS / path / to / my apk or http://myapp.com/app.ipa capabilities.setCapability("app", app.getAbsolutePath()); // Package name to run Android App capabilities.setCapability("appPackage", "com.example.testapp"); // The activity name of the Android activity to launch from the package capabilities.setCapability("appActivity", "com.example.testapp.MainActivity"); // Enable Unicode input method. Set it to true to enter Chinese characters. The default is false capabilities.setCapability("unicodeKeyboard", true); // After setting the 'Unicode keyboard' keyword to run Unicode test, reset the keyboard to its original state // If used alone, it will be ignored. The default value is ` false` capabilities.setCapability("resetKeyboard", true); // Set to true to overwrite the session every time it is started, otherwise an error will be reported in the second run, and a new session cannot be created capabilities.setCapability("sessionOverride", true); // Do not reset the application state before this session // Android do not stop the application, do not clear the application data, and do not uninstall apk // Do not destroy or close the SIM card after IOS test. Start the test run in any simulation run, or device insertion capabilities.setCapability("noReset", true); // Perform a complete reset // After the Android app is uninstalled and apk data is cleared // IOS uninstalls the application after the real device test, and destroys the simulator after the simulator test capabilities.setCapability("fullReset", false); // Sets the command timeout in seconds // When the timeout period is reached and no new command is received, Appium will assume that the client exits and automatically end the session 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 class (inheriting basepare class and storing use cases)
Script code:
package com.test.demo.testcases; import org.openqa.selenium.By; import org.testng.annotations.Test; import com.test.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
Document content:
<?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.testcases.CaseDemo" /> </classes> </test> </suite>
4,pom.xml
Added dependencies (TestNG, Appium):
<dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.11</version> <scope>test</scope> </dependency> <dependency> <groupId>io.appium</groupId> <artifactId>java-client</artifactId> <version>6.1.0</version> </dependency> </dependencies>
5. Start Appium service and execute the script (pom.xml. Right click Run as - > Maven test).
6. Execution result: console print result information: two test methods were executed successfully.
3,Maven+OkHttp
OkHttp+TestNG+Maven
Create My_Maven_OkHttp_Demo project
Get class (get request).
Post class (post request).
application.properties file (configuration file, setting request link).
1. Get class.
getCookie method: use the Get request to obtain the Cookie information of the response.
getWithCookie method: depending on the getCookie method, use the Get request to take the Cookie information obtained by the getCookie method as the request header Cookie.
Script code:
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 request * * @author wangmcn * */ public class Get { final int CONNECT_TIMEOUT = 30; final int READ_TIMEOUT = 30; final int WRITE_TIMEOUT = 30; // Create OkHttpClient object OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // Set connection timeout .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // Set read timeout .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // Set write timeout .retryOnConnectionFailure(true) // Automatic reconnection .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 { // The url of the splice test from the configuration file String uri = rb.getString("getCookie.uri"); String testUrl = url + uri; // Create Request object Request request = new Request.Builder() .url(testUrl) .get() .build(); // Get the Response object Response response = client.newCall(request).execute(); if(response.isSuccessful()){ System.out.println("Get response status: " + response.code()); System.out.println("Get response information: " + response.message()); System.out.println("Get web source code: " + response.body().string()); } // Get response header Headers responseHeader = response.headers(); System.out.println("Get response header: " + responseHeader); // Get Cookie this.store = responseHeader.get("Set-Cookie"); System.out.println("obtain Cookie: " + responseHeader.get("Set-Cookie")); // Clear and close thread pool client.dispatcher().executorService().shutdown(); // Clear and close connection pool client.connectionPool().evictAll(); } @Test(dependsOnMethods = { "getCookie" }) public void getWithCookie() throws IOException { // The url of the splice test from the configuration file String uri = rb.getString("get.cookie"); String testUrl = url + uri; // Create Request object Request request = new Request.Builder() .url(testUrl) .addHeader("Cookie", this.store) .get() .build(); // Get the Response object Response response = client.newCall(request).execute(); if(response.isSuccessful()){ System.out.println("Get response status: " + response.code()); System.out.println("Get response information: " + response.message()); System.out.println("Get web source code: " + response.body().string()); } // Clear and close thread pool client.dispatcher().executorService().shutdown(); // Clear and close connection pool client.connectionPool().evictAll(); } }
2. Post class.
getCookie method: use the Get request to obtain the Cookie information of the response.
postWithCookie method: rely on getCookie method, use Post request, take the Cookie information obtained by getCookie method as the request header Cookie, and send Json data.
Script code:
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 request * * @author wangmcn * */ public class Post { final int CONNECT_TIMEOUT = 30; final int READ_TIMEOUT = 30; final int WRITE_TIMEOUT = 30; // Create OkHttpClient object OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // Set connection timeout .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // Set read timeout .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // Set write timeout .retryOnConnectionFailure(true) // Automatic reconnection .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 { // The url of the splice test from the configuration file String uri = rb.getString("getCookie.uri"); String testUrl = url + uri; // Create Request object Request request = new Request.Builder() .url(testUrl) .get() .build(); // Get the Response object Response response = client.newCall(request).execute(); if(response.isSuccessful()){ System.out.println("Get response status: " + response.code()); System.out.println("Get response information: " + response.message()); System.out.println("Get web source code: " + response.body().string()); } // Get response header Headers responseHeader = response.headers(); System.out.println("Get response header: " + responseHeader); // Get Cookie this.store = responseHeader.get("Set-Cookie"); System.out.println("obtain Cookie: " + responseHeader.get("Set-Cookie")); // Clear and close thread pool client.dispatcher().executorService().shutdown(); // Clear and close connection pool client.connectionPool().evictAll(); } @Test(dependsOnMethods = { "getCookie" }) public void postWithCookie() throws IOException { // The url of the splice test from the configuration file String uri = rb.getString("post.cookie"); String testUrl = url + uri; // The data type is Json format MediaType JSON = MediaType.parse("application/json; charset=utf-8"); // Jason data String jsonStr = "{\"username\":\"admin\",\"password\":\"123456\"}"; // Get RequestBody object RequestBody body = RequestBody.create(JSON, jsonStr); // Create Request object Request request = new Request.Builder() .url(testUrl) .addHeader("Content-Type", "application/json;charset:utf-8") .addHeader("Cookie", this.store) .post(body) .build(); // Get the Response object Response response = client.newCall(request).execute(); if(response.isSuccessful()){ System.out.println("Get response status: " + response.code()); System.out.println("Get response information: " + response.message()); } // Convert the returned response result string into a Json object JSONObject resultJson = new JSONObject(response.body().string()); System.out.println("Get web source code: " + resultJson); // Assert Assert.assertEquals((String)resultJson.get("admin"), "success"); Assert.assertEquals((String)resultJson.get("status"), "1"); // Clear and close thread pool client.dispatcher().executorService().shutdown(); // Clear and close connection pool client.connectionPool().evictAll(); } }
3,testng.xml
Document content:
<?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,pom.xml
Added dependencies (TestNG, OkHttp, JSON):
<dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.11</version> <scope>test</scope> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.10.0</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> </dependency> </dependencies>
5. Execute the script (pom.xml. Right click Run as - > Maven test).
6. Print test results: 4 test results are executed successfully.
4,Maven+HttpClient
HttpClient+TestNG+Maven
Create My_Maven_HttpClient_Demo project
Get class (get request).
Post class (post request).
application.properties file (configuration file, setting request link).
1. Get class.
getCookie method: use the Get request to obtain the Cookie information of the response.
getWithCookie method: depending on the getCookie method, use the Get request to take the Cookie information obtained by the getCookie method as the request header Cookie.
Script code:
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 request * * @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 { // The url of the splice test from the configuration file String uri = rb.getString("getCookie.uri"); String testUrl = url + uri; // Create a CookieStore object cookieStore = new BasicCookieStore(); // Create CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom() // Set cookies .setDefaultCookieStore(cookieStore) .build(); // Create HttpGet object HttpGet httpget = new HttpGet(testUrl); // Set timeout RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(15000) // Set the connection timeout in milliseconds .setSocketTimeout(15000) // Timeout for requesting data, in milliseconds .setConnectionRequestTimeout(15000) // Sets the timeout for obtaining a Connection from the connect Manager, in milliseconds .build(); httpget.setConfig(requestConfig); // Execute Get request CloseableHttpResponse response = httpclient.execute(httpget); // Get response status System.out.println("Get response status: " + response.getStatusLine().getStatusCode()); // Get return entity HttpEntity entity = response.getEntity(); // Get web source code System.out.println("Get web source code:" + EntityUtils.toString(entity, "utf-8")); // Get response content type System.out.println("Get response content type:" + entity.getContentType().getValue()); // Get Cookie this.store = cookieStore.getCookies(); ListcookieList = cookieStore.getCookies(); for (Cookie cookies : cookieList) { System.out.println("Cookie: " + cookies.getName() + "; " + cookies.getValue()); } // Close streams and free system resources response.close(); // Close client httpclient.close(); } @Test(dependsOnMethods = { "getCookie" }) public void getWithCookie() throws ClientProtocolException, IOException { // The url of the splice test from the configuration file String uri = rb.getString("get.cookie"); String testUrl = url + uri; for (int i = 0; i < this.store.size(); i++) { // Create a CookieStore object cookieStore = new BasicCookieStore(); // Create a basicclientcookee object and add a 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); } // Create CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom() // Set cookies .setDefaultCookieStore(cookieStore) .build(); // Create HttpGet object HttpGet httpget = new HttpGet(testUrl); // Set timeout RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(15000) // Set the connection timeout in milliseconds .setSocketTimeout(15000) // Timeout for requesting data, in milliseconds .setConnectionRequestTimeout(15000) // Sets the timeout for obtaining a Connection from the connect Manager, in milliseconds .build(); httpget.setConfig(requestConfig); // Execute Get request CloseableHttpResponse response = httpclient.execute(httpget); // Get response status int statusCode = response.getStatusLine().getStatusCode(); System.out.println("Get response status: " + statusCode); if (statusCode == 200) { String result = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println("Get web source code:" + result); } // Close streams and free system resources response.close(); // Close client httpclient.close(); } }
2. Post class.
getCookie method: use the Get request to obtain the Cookie information of the response.
postWithCookie method: rely on getCookie method, use Post request, take the Cookie information obtained by getCookie method as the request header Cookie, and send Json data.
Script code:
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 request * * @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 { // The url of the splice test from the configuration file String uri = rb.getString("getCookie.uri"); String testUrl = url + uri; // Create a CookieStore object cookieStore = new BasicCookieStore(); // Create CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom() // Set cookies .setDefaultCookieStore(cookieStore) .build(); // Create HttpGet object HttpGet httpget = new HttpGet(testUrl); // Set timeout RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(15000) // Set the connection timeout in milliseconds .setSocketTimeout(15000) // Timeout for requesting data, in milliseconds .setConnectionRequestTimeout(15000) // Sets the timeout for obtaining a Connection from the connect Manager, in milliseconds .build(); httpget.setConfig(requestConfig); // Execute Get request CloseableHttpResponse response = httpclient.execute(httpget); // Get response status System.out.println("Get response status: " + response.getStatusLine().getStatusCode()); // Get return entity HttpEntity entity = response.getEntity(); // Get web source code System.out.println("Get web source code:" + EntityUtils.toString(entity, "utf-8")); // Get response content type System.out.println("Get response content type:" + entity.getContentType().getValue()); // Get Cookie this.store = cookieStore.getCookies(); ListcookieList = cookieStore.getCookies(); for (Cookie cookies : cookieList) { System.out.println("Cookie: " + cookies.getName() + "; " + cookies.getValue()); } // Close streams and free system resources response.close(); // Close client httpclient.close(); } @Test(dependsOnMethods = { "getCookie" }) public void postWithCookie() throws IOException { // The url of the splice test from the configuration file String uri = rb.getString("post.cookie"); String testUrl = url + uri; for (int i = 0; i < this.store.size(); i++) { // Create a CookieStore object cookieStore = new BasicCookieStore(); // Create a basicclientcookee object and add a 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); } // Create CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom() // Set cookies .setDefaultCookieStore(cookieStore) .build(); // Create an HttpPost object HttpPost httpPost = new HttpPost(testUrl); // Set timeout RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(15000) // Set the connection timeout in milliseconds .setSocketTimeout(15000) // Timeout for requesting data, in milliseconds .setConnectionRequestTimeout(15000) // Sets the timeout for obtaining a Connection from the connect Manager, in milliseconds .build(); httpPost.setConfig(requestConfig); // Set request header information httpPost.setHeader("content-type", "application/json; charset=utf-8"); // Add Json parameter JSONObject param = new JSONObject(); param.put("username", "admin"); param.put("password", "123456"); // Add parameter information to the method StringEntity entity = new StringEntity(param.toString(), "utf-8"); httpPost.setEntity(entity); // Execute Post request CloseableHttpResponse response = httpclient.execute(httpPost); // Get response results String result = EntityUtils.toString(response.getEntity(), "utf-8"); // Convert the returned response result string into a Json object JSONObject resultJson = new JSONObject(result); // Get web source code System.out.println("Get web source code:" + resultJson); // Assert Assert.assertEquals((String)resultJson.get("admin"), "success"); Assert.assertEquals((String)resultJson.get("status"), "1"); // Close streams and free system resources response.close(); // Close client httpclient.close(); } }
3,testng.xml
Document content:
<?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,pom.xml
Add JSON, testpng dependent:
<dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> </dependency> </dependencies>
5. Execute the script (pom.xml. Right click Run as - > Maven test).
6. Print test results: 4 test results are executed successfully.
If you think the article is good, please , like, share, watch and collect , because this will be the strongest driving force for me to continue to output more high-quality articles!
Here I recommend a software testing exchange group created by myself, QQ: 642830685. The group will share software testing resources, testing interview questions and testing industry information from time to time. You can actively exchange technology in the group, and big guys can answer questions and solve problems for you.