Testng 引用文件 ==》pom.xml

快捷键配置:Alt键+回车

<dependencies><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>7.4.0</version></dependency></dependencies>

Testng 基本注解和执行顺序

@Test              // 标识这是一个测试方法@BeforeMethod      // 这是在测试方法之前运行
@AfterMethod       // 这是在测试方法之后运行@BeforeClass       // 这是在类运行之前运行的方法,也就是调用当前类中的第一个方法之前运行测试用例开始执行一次
@AfterClass        // 这是在类运行之后运行的方法,当前类中的所有测试方法运行之后运行,测试用例结束执行一次
import org.testng.annotations.*;public class BasicAnnotation {@Test    // Alt+回车:快捷键配置testngpublic void testCase1(){System.out.println("Test这是测试用例1111");}@Test    // @Test标识这是一个测试用例方法public void testCase2(){System.out.println("Test这是测试用例2222");}@BeforeMethodpublic void beforeMethod(){System.out.println("BeforeMethod这是在测试方法之前运行");}@AfterMethodpublic void afterMethod(){System.out.println("AfterMethod这是在测试方法之后运行");}@BeforeClass                         // 测试用例开始执行一次public void beforeClass(){System.out.println("beforeClass 这是在类运行之前运行的方法,也就是调用当前类中的第一个方法之前运行");}@AfterClass                          // 测试用例结束执行一次public void afterClass(){System.out.println("afterClass 这是在类运行之后运行的方法,当前类中的所有测试方法运行之后运行");}@BeforeSuitepublic void f1(){System.out.println("@BeforeSuite套件测试,类运行之前运行之前运行");}@AfterSuitepublic void f2(){System.out.println("@AfterSuite套件测试,类运行之后运行之后运行");}
}

运行结果

@BeforeSuite       // 套件测试,类运行之前运行之前运行,所有测试运行之前运行
@AfterSuite        // 套件测试,类运行之后运行之后运行,所有测试运行之后运行
@BeforeTest        // 运行属于标记内的类的任何测试方法之前运行
@AfterTest         // 运行属于标记内的类的任何测试方法之后运行
import org.testng.annotations.Test;public class LoginTest {@Testpublic void loginTaoBao(){System.out.println("登陆成功");}
}
import org.testng.annotations.Test;public class Paytest {@Testpublic void PaySuccess(){System.out.println("支付成功");}
}
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;public class suiteConfig {@BeforeSuitepublic void beforeSuite(){System.out.println("Before Suite运行啦");}@AfterSuitepublic void afterSuite(){System.out.println("After Suite运行啦");}@BeforeTestpublic void BeforeTest(){System.out.println("Before Test运行啦");}@AfterTestpublic void AfterTest(){System.out.println("After Test运行啦");}
}

配置文件 ==》 testng.xml

<?xml version="1.0" encoding="UTF-8" ?>
<suite name="test"><test name="login"><classes><class name="testcase_testng.suite.suiteConfig"/><class name="testcase_testng.suite.LoginTest"/></classes></test><test name="Pay"><classes><class name="testcase_testng.suite.suiteConfig"/><class name="testcase_testng.suite.Paytest"/></classes></test></suite>

运行结果:

Before Suite 运行啦
Before Test 运行啦
登陆成功
After Test 运行啦
Before Test 运行啦
支付成功
After Test 运行啦
After Suite 运行啦

@Test(enabled = false)                // enabled = false 失效不执行、忽略测试
import org.testng.annotations.Test;public class lgnoreTest {@Testpublic void ignore1(){System.out.println("ignore1 执行!");}@Test(enabled = false)public void ignore2(){System.out.println("ignore2 执行!");}@Test(enabled = true)public void ignore3(){System.out.println("ignore3 执行!");}}// 执行结果ignore1 执行!
ignore3 执行!
@Test(description = "自己看的注释")      // 自己看的注释依赖测试
@Test(dependsOnMethods = "test2")       // dependsOnMethods = "test2" 先运行test2方法// alwaysRun = true 报错也会运行
import org.testng.annotations.Test;public class test {@Test(dependsOnMethods = "test2")public void test1() {System.out.println("test1...");}@Testpublic void test2() {System.out.println("test2...");}@Test(description = "自己看的注释")public void test3() {System.out.println("test3...");}
}
import org.testng.annotations.Test;public class DependTest {@Testpublic void test1(){System.out.println("test1 run");throw new RuntimeException();}@Test(dependsOnMethods = {"test1"})public void test2(){System.out.println("test2 run");}}// test2依赖于test1,当test1测试执行失败后,test2不再执行
方法组测试
@Test(groups = "server")                // 方法组测试
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;public class GroupsOnMethod {@Test(groups = "server")public void test1(){System.out.println("这是服务端组的测试方法1111");}@Test(groups = "server")public void test2(){System.out.println("这是服务端组的测试方法2222");}@Test(groups = "client")public void test3(){System.out.println("这是客户端组的测试方法3333");}@Test(groups = "client")public void test4(){System.out.println("这是客户端组的测试方法4444");}@BeforeGroups("server")public void beforeGroupsOnServer(){System.out.println("这是服务端组运行之前运行的方法!!!");}@AfterGroups("server")public void afterGroupsOnServer(){System.out.println("这是服务端组运行之后运行的方法!!!");}@BeforeGroups("client")public void beforeGroupsOnClient(){System.out.println("这是客户端组运行之前运行的方法!!!");}@AfterGroups("client")public void afterGroupsOnClient(){System.out.println("这是客户端组运行之后运行的方法!!!");}}

运行结果

这是服务端组运行之前运行的方法
这是服务端组的测试方法11111
这是服务端组的测试方法2222
这是服务端组运行之后运行的方法!!!!!
这是客户端组运行之前运行的方法
这是客户端组的测试方法33333
这是客户端组的测试方法4444
这是客户端组运行之后运行的方法!!!!!

类分组测试

import org.testng.annotations.Test;@Test(groups = "stu")
public class GroupsOnClass1 {public void stu1(){System.out.println("GroupsOnClass1中的stu1111运行");}public void stu2(){System.out.println("GroupsOnClass1中的stu2222运行");}
}
import org.testng.annotations.Test;@Test(groups = "stu")
public class GroupsOnClass2 {public void stu1(){System.out.println("GroupsOnClass222中的stu1运行");}public void stu2(){System.out.println("GroupsOnClass222中的stu2运行");}}
import org.testng.annotations.Test;@Test(groups = "teacher")
public class GroupsOnClass3 {public void teacher1(){System.out.println("GroupsOnClass3中的teacher1运行");}public void teacher2(){System.out.println("GroupsOnClass3中的teacher2运行");}}

配置文件==》groupOnClass.xml

<?xml version="1.0" encoding="UTF-8" ?><suite name="suitename"><test name="runAll"><classes><class name="com.course.testng.groups.GroupsOnClass1"/><class name="com.course.testng.groups.GroupsOnClass2"/><class name="com.course.testng.groups.GroupsOnClass3"/></classes></test><test name="onlyRunStu"><groups><run><include name="stu"/></run></groups><classes><class name="com.course.testng.groups.GroupsOnClass1"/><class name="com.course.testng.groups.GroupsOnClass2"/><class name="com.course.testng.groups.GroupsOnClass3"/></classes></test></suite>

运行结果

GroupsOnClass1中的stu1111运行
GroupsOnClass1中的stu2222运行
GroupsOnClass222中的stu1运行
GroupsOnClass222中的stu2运行
GroupsOnClass3中的teacher1运行
GroupsOnClass3中的teacher2运行

GroupsOnClass1中的stu1111运行
GroupsOnClass1中的stu2222运行
GroupsOnClass222中的stu1运行
GroupsOnClass222中的stu2运行

异常测试 

import org.testng.annotations.Test;public class ExpectedException {/*** 什么时候会用到异常测试??* 在我们期望结果为某一个异常的时候* 比如:我们传入了某些不合法的参数,程序抛出了异常* 也就是说我的语气结果就是这个异常。*///    这是一个测试结果会失败的异常测试@Test(expectedExceptions = RuntimeException.class)public void runTimeExceptionFailed(){System.out.println("这是一个失败的异常测试");}//    这是一个成功的异常测试@Test(expectedExceptions = RuntimeException.class)public void runTimeExceptionSuccess(){System.out.println("这是我的异常测试");throw new RuntimeException();}}

参数化测试和xml文件参数化

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;public class ParamterTest {@Test@Parameters({"name","age"})public void paramTest1(String name,int age){System.out.println("name = " + name + ";  age = " + age);}}

 Paramter.xml 配置文件

<?xml version="1.0" encoding="UTF-8" ?><suite name="parameter"><test name="param"><classes><parameter name="name" value="zhangsan"/><parameter name="age" value="10"/><class name="com.course.testng.paramter.ParamterTest"/></classes></test></suite>

对象传递参数化

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;import java.lang.reflect.Method;public class DataProviderTest {@Test(dataProvider = "data")public void testDataProvider(String name,int age){System.out.println("name =" + name +"; age=" + age);}@DataProvider(name="data")public Object[][] providerData(){Object[][] o = new Object[][]{{"zhangsan",10},{"lisi",20},{"wangwu",30}};return o;}@Test(dataProvider = "methodData")public void test1(String name,int age){System.out.println("test111方法 name="+name+";age="+age);}@Test(dataProvider = "methodData")public void test2(String name,int age){System.out.println("test222方法 name="+name+";age="+age);}@DataProvider(name="methodData")public Object[][] methodDataTest(Method method){Object[][] result=null;if(method.getName().equals("test1")){result = new Object[][]{{"zhangsan",20},{"lisi",25}};}else if(method.getName().equals("test2")){result = new Object[][]{{"wangwu",50},{"zhaoliu",60}};}return result;}}

多线程测试

import org.testng.annotations.Test;public class MultiThreadOnAnnotion {@Test(invocationCount = 10,threadPoolSize = 3)public void test(){System.out.println(1);System.out.printf("Thread Id : %s%n",Thread.currentThread().getId());}}
import org.testng.annotations.*;public class BasicAnnotation {//最基本的注解,用来把方法标记为测试的一部分@Testpublic void testCase1(){System.out.printf("Thread Id : %s%n",Thread.currentThread().getId());System.out.println("Test这是测试用例1");}@Testpublic void testCase2(){System.out.printf("Thread Id : %s%n",Thread.currentThread().getId());System.out.println("Test这是测试用例2");}@BeforeMethodpublic void beforeMethod(){System.out.println("BeforeMethod这是在测试方法之前运行的");}@AfterMethodpublic void afterMethod(){System.out.println("AfterMethod这是在测试方法之后运行的");}@BeforeClasspublic void beforeClass(){System.out.println("beforeClass这是在类运行之前运行的方法");}@AfterClasspublic void afterClass(){System.out.println("afterClass这是在类运行之后运行的方法");}@BeforeSuitepublic void beforeSuite(){System.out.println("BeforeSuite测试套件");}@AfterSuitepublic void afterSuite(){System.out.println("AfterSuite测试套件");}
}
import org.testng.annotations.Test;public class MultiThreadOnXml {@Testpublic void test1(){System.out.printf("Thread Id : %s%n",Thread.currentThread().getId());}@Testpublic void test2(){System.out.printf("Thread Id : %s%n",Thread.currentThread().getId());}@Testpublic void test3(){System.out.printf("Thread Id : %s%n",Thread.currentThread().getId());}}
tests级别:不同的test tag下的用例可以在不同的线程下执行相同的test tag下的用例只能在同一个线程中去执行classs级别:相同的class tag 下的用例在同一个线程中执行不同的class tag 下的用例可以在不同的线程中执行methods级别:所有用例都可以在不同的线程下去执行thread-count:代表了最大并发线程数xml文件配置这种方式不能指定线程池,只有方法上才可以指定线程池
<?xml version="1.0" encoding="UTF-8" ?><suite name="thread" parallel="methods" thread-count="3"><test name = "demo1"><classes name="d"><class name="com.course.testng.multiThread.MultiThreadOnXml"/><class name="com.course.testng.BasicAnnotation"/><class name="com.course.testng.multiThread.MultiThreadOnXml"/></classes><classes name="d1"><class name="com.course.testng.multiThread.MultiThreadOnXml"/><class name="com.course.testng.BasicAnnotation"/><class name="com.course.testng.multiThread.MultiThreadOnXml"/></classes></test><test name = "demo2"><classes name="d3"><class name="com.course.testng.BasicAnnotation"/></classes></test></suite>

超时测试

import org.testng.annotations.Test;public class TimeOutTest {@Test(timeOut = 3000)//单位为毫秒值public void testSuccess() throws InterruptedException {Thread.sleep(2000);}@Test(timeOut = 2000)public void testFailed() throws InterruptedException {Thread.sleep(3000);}
}

Testng测试报告

import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;public class TestMethodsDemo {@Testpublic void test1(){Assert.assertEquals(1,2);}@Testpublic void test2(){Assert.assertEquals(1,1);}@Testpublic void test3(){Assert.assertEquals("aaa","aaa");}@Testpublic void logDemo(){Reporter.log("这是我们自己写的日志");throw new RuntimeException("这是我自己的运行时异常");}}

配置文件和日志模板文件

<?xml version="1.0" encoding="UTF-8" ?><suite name="我自己的接口测试套件"><test name="这些是测试模块"><classes><class name="com.tester.extend.demo.TestMethodsDemo"><methods><include name="test1"/><include name="test2"/><include name="test3"/><include name="logDemo"/></methods></class></classes></test><listeners><listener class-name="com.tester.extend.demo.ExtentTestNGIReporterListener" /></listeners></suite>
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.ResourceCDN;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.model.TestAttribute;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
import org.testng.*;
import org.testng.xml.XmlSuite;import java.io.File;
import java.util.*;public class ExtentTestNGIReporterListener implements IReporter {//生成的路径以及文件名private static final String OUTPUT_FOLDER = "test-output/";private static final String FILE_NAME = "index.html";private ExtentReports extent;@Overridepublic void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {init();boolean createSuiteNode = false;if(suites.size()>1){createSuiteNode=true;}for (ISuite suite : suites) {Map<String, ISuiteResult> result = suite.getResults();//如果suite里面没有任何用例,直接跳过,不在报告里生成if(result.size()==0){continue;}//统计suite下的成功、失败、跳过的总用例数int suiteFailSize=0;int suitePassSize=0;int suiteSkipSize=0;ExtentTest suiteTest=null;//存在多个suite的情况下,在报告中将同一个一个suite的测试结果归为一类,创建一级节点。if(createSuiteNode){suiteTest = extent.createTest(suite.getName()).assignCategory(suite.getName());}boolean createSuiteResultNode = false;if(result.size()>1){createSuiteResultNode=true;}for (ISuiteResult r : result.values()) {ExtentTest resultNode;ITestContext context = r.getTestContext();if(createSuiteResultNode){//没有创建suite的情况下,将在SuiteResult的创建为一级节点,否则创建为suite的一个子节点。if( null == suiteTest){resultNode = extent.createTest(r.getTestContext().getName());}else{resultNode = suiteTest.createNode(r.getTestContext().getName());}}else{resultNode = suiteTest;}if(resultNode != null){resultNode.getModel().setName(suite.getName()+" : "+r.getTestContext().getName());if(resultNode.getModel().hasCategory()){resultNode.assignCategory(r.getTestContext().getName());}else{resultNode.assignCategory(suite.getName(),r.getTestContext().getName());}resultNode.getModel().setStartTime(r.getTestContext().getStartDate());resultNode.getModel().setEndTime(r.getTestContext().getEndDate());//统计SuiteResult下的数据int passSize = r.getTestContext().getPassedTests().size();int failSize = r.getTestContext().getFailedTests().size();int skipSize = r.getTestContext().getSkippedTests().size();suitePassSize += passSize;suiteFailSize += failSize;suiteSkipSize += skipSize;if(failSize>0){resultNode.getModel().setStatus(Status.FAIL);}resultNode.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",passSize,failSize,skipSize));}buildTestNodes(resultNode,context.getFailedTests(), Status.FAIL);buildTestNodes(resultNode,context.getSkippedTests(), Status.SKIP);buildTestNodes(resultNode,context.getPassedTests(), Status.PASS);}if(suiteTest!= null){suiteTest.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",suitePassSize,suiteFailSize,suiteSkipSize));if(suiteFailSize>0){suiteTest.getModel().setStatus(Status.FAIL);}}}
//        for (String s : Reporter.getOutput()) {
//            extent.setTestRunnerOutput(s);
//        }extent.flush();}private void init() {//文件夹不存在的话进行创建File reportDir= new File(OUTPUT_FOLDER);if(!reportDir.exists()&& !reportDir .isDirectory()){reportDir.mkdir();}ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);// 设置静态文件的DNS//怎么样解决cdn.rawgit.com访问不了的情况htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);htmlReporter.config().setDocumentTitle("api自动化测试报告");htmlReporter.config().setReportName("api自动化测试报告");htmlReporter.config().setChartVisibilityOnOpen(true);htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);htmlReporter.config().setTheme(Theme.STANDARD);htmlReporter.config().setCSS(".node.level-1  ul{ display:none;} .node.level-1.active ul{display:block;}");extent = new ExtentReports();extent.attachReporter(htmlReporter);extent.setReportUsesManualConfiguration(true);}private void buildTestNodes(ExtentTest extenttest, IResultMap tests, Status status) {//存在父节点时,获取父节点的标签String[] categories=new String[0];if(extenttest != null ){List<TestAttribute> categoryList = extenttest.getModel().getCategoryContext().getAll();categories = new String[categoryList.size()];for(int index=0;index<categoryList.size();index++){categories[index] = categoryList.get(index).getName();}}ExtentTest test;if (tests.size() > 0) {//调整用例排序,按时间排序Set<ITestResult> treeSet = new TreeSet<ITestResult>(new Comparator<ITestResult>() {@Overridepublic int compare(ITestResult o1, ITestResult o2) {return o1.getStartMillis()<o2.getStartMillis()?-1:1;}});treeSet.addAll(tests.getAllResults());for (ITestResult result : treeSet) {Object[] parameters = result.getParameters();String name="";//如果有参数,则使用参数的toString组合代替报告中的namefor(Object param:parameters){name+=param.toString();}if(name.length()>0){if(name.length()>50){name= name.substring(0,49)+"...";}}else{name = result.getMethod().getMethodName();}if(extenttest==null){test = extent.createTest(name);}else{//作为子节点进行创建时,设置同父节点的标签一致,便于报告检索。test = extenttest.createNode(name).assignCategory(categories);}//test.getModel().setDescription(description.toString());//test = extent.createTest(result.getMethod().getMethodName());for (String group : result.getMethod().getGroups())test.assignCategory(group);List<String> outputList = Reporter.getOutput(result);for(String output:outputList){//将用例的log输出报告中test.debug(output);}if (result.getThrowable() != null) {test.log(status, result.getThrowable());}else {test.log(status, "Test " + status.toString().toLowerCase() + "ed");}test.getModel().setStartTime(getTime(result.getStartMillis()));test.getModel().setEndTime(getTime(result.getEndMillis()));}}}private Date getTime(long millis) {Calendar calendar = Calendar.getInstance();calendar.setTimeInMillis(millis);return calendar.getTime();}
}

HttpClient 框架

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>Http_Client</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>7.4.0</version></dependency><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20170516</version></dependency></dependencies></project>

get请求无参

public class MyHttpClient {@Testpublic void test1() throws IOException {// 用来请求结果String result;String url = "http://www.tpshop.com/index.php?m=Home&c=User&a=verify";HttpGet get = new HttpGet(url);// 这个是用来执行那个get方法HttpClient client = new DefaultHttpClient();HttpResponse response = client.execute(get);result = EntityUtils.toString(response.getEntity(),"utf-8");System.out.println(result);}
}

实际工作是基础URl等基本信息放在配置文件中 ==》application.properties

test.url = http://www.tpshop.comtest_url= http://www.litemall360.com:8080getCookie.url = /index.php?m=Home&c=User&a=verifylogin.url = /index.php?m=Home&c=User&a=do_loginlogin_url = /wx/auth/login
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;import java.io.IOException;
import java.util.List;
import java.util.ResourceBundle;public class MyCookiesForGet {public String url;private ResourceBundle bundle;// 存储cookies信息private CookieStore store;@BeforeTestpublic void beforeTest(){bundle = ResourceBundle.getBundle("application");url = bundle.getString("test.url");}@Testpublic void testGetCookies() throws IOException {String result;// 从配置文件中拼接urlString uri = bundle.getString("getCookie.url");String testurl = this.url + uri;HttpGet get_cookies_url = new HttpGet(testurl);DefaultHttpClient client = new DefaultHttpClient();HttpResponse response = client.execute(get_cookies_url);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(name + value);}}
}

post请求、表单格式参数、携带cookies

public class MyCookiesForGet {public String url;private ResourceBundle bundle;// 存储cookies信息private CookieStore store;@BeforeTestpublic void beforeTest(){bundle = ResourceBundle.getBundle("application", Locale.CANADA);url = bundle.getString("test.url");}@Testprivate void testPostMethod() throws IOException {String uri = bundle.getString("login.url");// 地址拼接String testUrl = this.url + uri;// 声明一个post方法HttpPost httpPost = new HttpPost(testUrl);// 添加参数JSONObject param = new JSONObject();param.put("username","15788888888");param.put("password","123456");param.put("verify_code",888);// 设置请求头信息、设置headershttpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");// 将参数添加到方法中StringEntity entity = new StringEntity(param.toString(),"utf-8");httpPost.setEntity(entity);// 声明一个对象来进行响应结果的存储用来进行方法的执行,并设置cookies信息CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(this.store).build();//执行post的方法并得到响应结果CloseableHttpResponse response3 = httpclient.execute(httpPost);//就是判断返回结果是否符合预期int statusCode = response3.getStatusLine().getStatusCode();System.out.println("statusCode = "+ statusCode);String result = EntityUtils.toString(response3.getEntity(),"utf-8");if (statusCode == 200){System.out.println(result);}else {System.out.println("登陆失败!");}// 处理结果,断言是否符合预期// 将返回的响应结果字符串转化成json对象JSONObject resultJson = new JSONObject(result);// 具体的判断返回结果的值// 获取到结果值System.out.println(resultJson);
//        String success = (String) resultJson.get("errmsg");
//        System.out.println(success);
//        Assert.assertEquals("成功",success);}}

post请求、json格式参数、携带cookies

public class MyCookiesForPost {public String url;private ResourceBundle bundle;// 存储cookies信息private CookieStore store;@BeforeTestpublic void beforeTest(){bundle = ResourceBundle.getBundle("application", Locale.CANADA);url = bundle.getString("test_url");}@Testprivate void testPostMethod() throws IOException {String uri = bundle.getString("login_url");// 地址拼接String testUrl = this.url + uri;// 声明一个post方法HttpPost httpPost = new HttpPost(testUrl);// 添加参数JSONObject param = new JSONObject();
//        param.put("username","15708460952");
//        param.put("password","123456");
//        param.put("verify_code",888);param.put("username","user123");param.put("password","user123");// 设置请求头信息、设置headershttpPost.setHeader("Content-Type","application/json;charset=UTF-8");// 将参数添加到方法中StringEntity entity = new StringEntity(param.toString(),"utf-8");httpPost.setEntity(entity);// 声明一个对象来进行响应结果的存储用来进行方法的执行,并设置cookies信息CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(this.store).build();//执行post的方法并得到响应结果CloseableHttpResponse response3 = httpclient.execute(httpPost);//就是判断返回结果是否符合预期int statusCode = response3.getStatusLine().getStatusCode();System.out.println("statusCode = "+ statusCode);String result = EntityUtils.toString(response3.getEntity(),"utf-8");if (statusCode == 200){System.out.println(result);}else {System.out.println("登陆失败!");}// 处理结果,断言是否符合预期// 将返回的响应结果字符串转化成json对象JSONObject resultJson = new JSONObject(result);// 具体的判断返回结果的值// 获取到结果值
//        System.out.println(resultJson);String success = (String) resultJson.get("errmsg");System.out.println(success);Assert.assertEquals("成功",success);}
}

处理get请求获取cookies,关联接口post请求携带cookies

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
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.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.util.List;
import java.util.ResourceBundle;public class get_cookies_HttpClient {public String url;private ResourceBundle bundle;// 存储cookies信息private CookieStore store;@BeforeTestpublic void beforetest(){bundle = ResourceBundle.getBundle("application");url = bundle.getString("test.url");}@Testprivate void testGetCookies1() throws Exception {String result;String uri = bundle.getString("getCookie.url");String testurl = this.url + uri;HttpGet get_cookies_url = new HttpGet(testurl);DefaultHttpClient client = new DefaultHttpClient();HttpResponse response = client.execute(get_cookies_url);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(name + value);}}@Testprivate void testPostMethod2() throws Exception {String uri2 = bundle.getString("login.url");// 地址拼接String testUrl = this.url + uri2;// 声明一个post方法HttpPost httpPost = new HttpPost(testUrl);// 添加参数JSONObject param = new JSONObject();param.put("username","15708460952");param.put("password","123456");param.put("verify_code",8888);// 设置请求头信息、设置headershttpPost.setHeader("Content-Type","application/json;charset=UTF-8");// 将参数添加到方法中StringEntity entity = new StringEntity(param.toString(),"utf-8");httpPost.setEntity(entity);// 声明一个对象来进行响应结果的存储用来进行方法的执行,并设置cookies信息System.out.println(this.store);CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(this.store).build();//执行post的方法并得到响应结果CloseableHttpResponse response3 = httpclient.execute(httpPost);//就是判断返回结果是否符合预期int statusCode = response3.getStatusLine().getStatusCode();System.out.println("statusCode = "+ statusCode);String result = EntityUtils.toString(response3.getEntity(),"utf-8");if (statusCode == 200){System.out.println(result);}else {System.out.println("登陆失败!");}// 处理结果,断言是否符合预期// 将返回的响应结果字符串转化成json对象JSONObject resultJson = new JSONObject(result);// 具体的判断返回结果的值// 获取到结果值System.out.println(resultJson);String success = (String) resultJson.get("msg");System.out.println(success);Assert.assertEquals("登陆成功",success);}}

java接口自动化-Testng框架、HttpClient框架相关推荐

  1. Java接口自动化之TestNG单元测试框架(一)

    上一篇Java接口自动化系列文章:Java接口自动化之log4j日志框架,主要介绍log4j日志介绍.日志三大组成部分及日志实战. 以下主要介绍TestNG的简介.@Test注解及其属性. 01 Te ...

  2. Java接口自动化之Maven工具使用

    VOL 190 30 2020-12 今天距2021年1天 这是ITester软件测试小栈第190次推文 点击上方蓝字"ITester软件测试小栈"关注我,每周一.三.五早上 08 ...

  3. java接口自动化书籍_java接口自动化优化(一)

    优化extentreports在线样式改为离线加载自己项目下的样式 主要解决extentreports在线加载失败问题 上篇文章介绍了通过testng编写用例后使用extentreports作为测试报 ...

  4. java接口自动化(四) - 企业级代码管理工具Git的应用

    1.简介 首先我们自己需要将自己的代码上传到GitHub上边做好备份.用来避免万一由于某些不可控的非人为因素或者人为因素造成的代码丢失.而且GitHub是一个开源的代码管理工具.所以宏哥这里再次介绍一 ...

  5. java接口自动化Excel占位符_基于maven+java+TestNG+httpclient+poi+jsonpath+ExtentReport的接口自动化测试框架...

    接口自动化框架 项目说明 本框架是一套基于maven+java+TestNG+httpclient+poi+jsonpath+ExtentReport而设计的数据驱动接口自动化测试框架,TestNG ...

  6. java接口自动化(三) - 手工接口测试到自动化框架设计之鸟枪换炮

    1.简介 上一篇宏哥介绍完了接口用例设计,那么这一章节,宏哥就趁热打铁介绍一下,接口测试工具.然后小伙伴们或者童鞋们就可以用接口测试工具按照设计好的测试用例开始执行用例进行接口手动测试了.关于手动测试 ...

  7. java接口自动化监控_java接口自动化(三) - 手工接口测试到自动化框架设计之鸟枪换炮...

    1.简介 上一篇宏哥介绍完了接口用例设计,那么这一章节,宏哥就趁热打铁介绍一下,接口测试工具.然后小伙伴们或者童鞋们就可以用接口测试工具按照设计好的测试用例开始执行用例进行接口手动测试了.关于手动测试 ...

  8. Java接口自动化框架系列07:Web接口自动化测试框架设计思路

    1.Java web接口自动化框架 框架名称:Java+Maven+httpClients+TestNg+Allure (因本次只讲解java部分,未包括git和jenkins,如果是包括git和je ...

  9. java接口自动化(一) - 接口自动化测试整体认知 - 开山篇(超详解)

    简介 了解什么是接口和为什么要做接口测试.并且知道接口自动化测试应该学习哪些技术以及接口自动化测试的落地过程.其实这些基本上在python接口自动化的文章中已经详细的介绍过了,不清楚的可以过去看看.了 ...

最新文章

  1. WEB Struts2 中OGNL的用法
  2. reactjs大列表大表格渲染组件:react-virtualized
  3. apk图标存放位置_安卓系统下安装完apk程序后,具体的文件夹位置在哪里呢?
  4. C语言运算符及其优先级汇总表口诀
  5. 原生JS实现各种经典网页特效——Banner图滚动、选项卡切换、广告弹窗等
  6. 趣味俄罗斯方块代码分享(C语言)
  7. flash小黄油安卓_从Android 1到10 一起回顾伴随我们成长的安卓系统
  8. 【C语言】||(或) (且)
  9. android 加速度传感器测步数,基于加速度传感器的运动步数检测算法研究
  10. Linux下安装配置各种软件和服务
  11. 【华为机试真题 JAVA】字符串子序列II-100
  12. jq点击图片展示预览效果
  13. log4j日志信息配置文件详解
  14. LeetCode 427. 建立四叉树
  15. Resources.getSystem() 和 getResources()
  16. ffmpeg使用记录--解决了压制的视频在安卓不播放的问题
  17. 万物皆可NFT,UTON NFT正式上线内测
  18. PS新手教程:加深减淡工具使用方法
  19. Android蜘蛛网评分
  20. Vue笔记18_插槽slot

热门文章

  1. FLTK学习-2-新手入门参考
  2. 使用 SQL Server 创建唯一索引
  3. office下载与安装
  4. Win32的入口函数WinMain前面的WINAPI有什么意义?
  5. (转)科普:SATA、PCIe、AHCI、NVMe
  6. AllenBradley罗克韦尔CIP通信协议介绍 C# AllenBradley(CIP)读写操作PLC数据 C#罗克韦尔(CIP)PLC通信
  7. 关于直通车与万相台的区别,你知道多少
  8. 微信小程序引入less并引入公共样式
  9. 微信小程序——消息推送参数
  10. PyTorch深度学习实践 Lecture09 Softmax 分类器