Java接口自動化測試實戰筆記


原文地址:https://www.jianshu.com/p/1f357b849c87

Java接口自動化測試實戰筆記

綜述

  • 需求階段:項目立項、產品設計、需求文檔
  • 研發階段:UI 設計、前端開發、后端開發、測試設計、測試開發(並行)
  • 測試階段:環境搭建、多項測試執行、BUG 修復、測試報告
  • 項目上線:線上回歸測試、上線報告、添加監控

接口測試范圍:

功能測試:等價類划分法、邊界值分析法、錯誤推斷法、因果圖法、判定表驅動法、正交試驗法、功能圖法、場景法

異常測試:數據異常(null,"",數據類型)、環境異常(負載均衡架構、冷熱備份)

性能測試(狹義):負載測試、壓力測試或強度測試、並發測試、穩定性測試或可靠性測試

手工接口測試的常用工具

  • Postman
  • HttpRequest(Firefox 插件)
  • Fiddler(具備抓包和發送請求功能)
  • 半自動化:Jmeter(結果統計方面不完善)

自動化框架的設計

  • 顯示層:測試報告
  • 控制層:邏輯驗證
  • 持久層:測試用例存儲(數據驅動)

測試代碼:https://github.com/alanhou7/AutoTest

代碼管理工具Git

安裝客戶端

yum install -y git # Linux https://git-scm.com/downloads brew install git # Mac git --version # 配置 SSH key ssh-keygen -t rsa -C "email address" cd ~/.ssh # 復制 id_rsa.pub到 GitHub 中 # 配置多個 SSH key(創建.ssh/config 文件,多賬號可以為 id_rsa,id_rsa.pub 重命名並在 config 中進行對應配置) Host github.com HostName github.com User git_username IdentityFile /Users/alan/.ssh/id_rsa.pub 

Git命令

# 克隆項目到本地 git clone git@github.com/xxx.xxx.git # 查看狀態 git status # 添加內容 git add xxx git commit -m "comment" # 推送到 GitHub git push # 拉取到本地 git pull # 查看本地分支 git branch # 查看遠端分支 git branch -a # 本地創建分支 git checkout -b branch1 # 推送分支 git push --set-upstream origin branch1 # 切換分支 git checkout master # 刪除本地分支 git branch -d branch1 # 刪除遠程分支 git branch -r -d origin/branch1 git push origin :branch1 # 合並指定分支內容到當前分支 git merge branch1 # 合並沖突通過<<<<<<<HEAD ... >>>>>>> branchname在文件中提示 # 回退到上一個版本,HEAD后添加幾個^就是向前回退幾個版本 git reset --hard HEAD^ # 或指定向前回退多少個版本 git reset -hard HEAD~10 # 查看歷史版本號 git reflog # 回退到指定版本號 git reset -hard version_no 

測試框架 TestNG

TestNG比 Junit 涵蓋功能更全面、適合復雜的集成測試,Junit 更適合隔離性比較強的單元測試

完整代碼 Git 倉庫

# pom.xml
<dependencies> ... <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.10</version> </dependency> </dependencies> 

執行順序

//最基本的注解,用來把方法標記為測試的一部分 @Test //BeforeMethod 是在測試方法之前運行的 @BeforeMethod //AfterMethod 是在測試方法之后運行的 @AfterMethod //BeforeClass 是在類之前運行的方法 @BeforeClass //AfterClass 是在類之后運行的方法 @AfterClass //BeforeSuite測試套件在BeforeClass之前運行 @BeforeSuite //AfterSuite測試套件在AfterClass之后運行 @AfterSuite 

BeforeMethod和AfterMethod 會在類中的每個@Test 裝飾的方法之前和之后運行

//忽略測試
@Test(enabled = false)

//分組測試
@Test(groups = "xxx")
//指定名稱組運行之前運行的方法
@BeforeGroups("xxx")
//指定名稱組運行之后運行的方法
@AfterGroups("xxx")

//類的分組測試(@Test(groups = "xxx")加在類上),以下配置通過<groups>部分的配置將僅運行組名為 stu 的類 <?xml version="1.0" encoding="UTF-8" ?> <suite name="suitename"> <test name="onlyRunStu"> <groups> <run> <include name="stu" /> </run> </groups> <classes> <class name="org.alanhou.testng.groups.GroupsOnClass1"></class> <class name="org.alanhou.testng.groups.GroupsOnClass2"></class> <class name="org.alanhou.testng.groups.GroupsOnClass3"></class> </classes> </test> </suite> //異常測試 @Test(expectedExceptions = RuntimeException.class) //依賴測試(所依賴的方法執行成功了都會執行當前方法) @Test(dependsOnMethods = {"xxx"}) //參數化測試 @Parameters({"name","age"}) //類添加 //xml設置參數 <suite name="parameter"> <test name="param"> <classes> <parameter name="name" value="Jack" /> <parameter name="age" value="10" /> <class name="org.alanhou.testng.parameter.ParameterTest"></class> </classes> </test> </suite> //此外可以通過 DataProvider 進行參數傳遞 //多線程測試 //獲取當前線程 ID Thread.currentThread().getId() //parallel指定線程級別(tests,class,methods),thread-count指定線程數 <suite name="thread" parallel="methods" thread-count="3"> //超時測試 @Test(timeOut = 3000) //單位為毫秒 

測試報告

推薦:ExtentReports 測試報告

其它:TestNG 測試報告、ReportNG 測試報告

完整代碼 Git 倉庫

//默認的監聽器生成的報告 CSS 需翻牆才能加載
<!--<listener class-name="com.vimalselvam.testng.listener.ExtentTestNgFormatter" />--> <!--<listener class-name="com.tester.extend.demo.ExtentTestNGIReporterListenerOld" />--> <listener class-name="com.tester.extend.demo.ExtentTestNGIReporterListener" /> //最后一個文件根據網上文件添加以下語句以解決cdn.rawgit.com 訪問不了的情況 htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS); 
TestNG extent reports

Mock 接口框架

Moco 框架

演示代碼 Git 倉庫

// http 外還支持 https,socket,8888可修改為其它的端口號 java -jar ./moco-runner-0.12.0-standalone.jar http -p 8888 -c startup1.json //GET請求可直接在瀏覽器中訪問同,POST 請求可借助於 Postman 或 Jmeter brew install jmeter open /usr/local/bin/jmeter //或者直接輸入 jmeter //新建線程組>HTTP請求(POST請求)以及結果樹(查看結果) //GET在 request中使用 queries 傳參,POST使用 forms //也可使用 json 來進行 POST/GET請求 //header,cookies 可用添加頭信息和 cookies 信息 //redirectTo 添加重定向信息 
Jmeter 請求界面

HTTP 協議接口

Requests Header (請求頭)

Header 解釋 示例
Accept 指定客戶端能夠接收的內容類型 Accept: text/plain, text/html
Accept-Charset 瀏覽器可以接受的字符編碼集。 Accept-Charset: iso-8859-5
Accept-Encoding 指定瀏覽器可以支持的web服務器返回內容壓縮編碼類型。 Accept-Encoding: compress, gzip
Accept-Language 瀏覽器可接受的語言 Accept-Language: en,zh
Accept-Ranges 可以請求網頁實體的一個或者多個子范圍字段 Accept-Ranges: bytes
Authorization HTTP授權的授權證書 Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Cache-Control 指定請求和響應遵循的緩存機制 Cache-Control: no-cache
Connection 表示是否需要持久連接。(HTTP 1.1默認進行持久連接) Connection: close
Cookie HTTP請求發送時,會把保存在該請求域名下的所有cookie值一起發送給web服務器。 Cookie: $Version=1; Skin=new;
Content-Length 請求的內容長度 Content-Length: 348
Content-Type 請求的與實體對應的MIME信息 Content-Type: application/x-www-form-urlencoded
Date 請求發送的日期和時間 Date: Tue, 15 Nov 2010 08:12:31 GMT
Expect 請求的特定的服務器行為 Expect: 100-continue
From 發出請求的用戶的Email From: user@email.com
Host 指定請求的服務器的域名和端口號 Host: www.baidu.com
If-Match 只有請求內容與實體相匹配才有效 If-Match: “737060cd8c284d8af7ad3082f209582d”
If-Modified-Since 如果請求的部分在指定時間之后被修改則請求成功,未被修改則返回304代碼 If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
If-None-Match 如果內容未改變返回304代碼,參數為服務器先前發送的Etag,與服務器回應的Etag比較判斷是否改變 If-None-Match: “737060cd8c284d8af7ad3082f209582d”
If-Range 如果實體未改變,服務器發送客戶端丟失的部分,否則發送整個實體。參數也為Etag If-Range: “737060cd8c284d8af7ad3082f209582d”
If-Unmodified-Since 只在實體在指定時間之后未被修改才請求成功 If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT
Max-Forwards 限制信息通過代理和網關傳送的時間 Max-Forwards: 10
Pragma 用來包含實現特定的指令 Pragma: no-cache
Proxy-Authorization 連接到代理的授權證書 Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Range 只請求實體的一部分,指定范圍 Range: bytes=500-999
Referer 先前網頁的地址,當前請求網頁緊隨其后,即來路 Referer: https://www.baidu.com/
TE 客戶端願意接受的傳輸編碼,並通知服務器接受接受尾加頭信息 TE: trailers,deflate;q=0.5
Upgrade 向服務器指定某種傳輸協議以便服務器進行轉換(如果支持) Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
User-Agent User-Agent的內容包含發出請求的用戶信息 User-Agent: Mozilla/5.0 (Linux; X11)
Via 通知中間網關或代理服務器地址,通信協議 Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning 關於消息實體的警告信息 Warn: 199 Miscellaneous warning

Responses Header(響應頭)

Header 解釋 示例
Accept-Ranges 表明服務器是否支持指定范圍請求及哪種類型的分段請求 Accept-Ranges: bytes
Age 從原始服務器到代理緩存形成的估算時間(以秒計,非負) Age: 12
Allow 對某網絡資源的有效的請求行為,不允許則返回405 Allow: GET, HEAD
Cache-Control 告訴所有的緩存機制是否可以緩存及哪種類型 Cache-Control: no-cache
Content-Encoding web服務器支持的返回內容壓縮編碼類型。 Content-Encoding: gzip
Content-Language 響應體的語言 Content-Language: en,zh
Content-Length 響應體的長度 Content-Length: 348
Content-Location 請求資源可替代的備用的另一地址 Content-Location: /index.htm
Content-MD5 返回資源的MD5校驗值 Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
Content-Range 在整個返回體中本部分的字節位置 Content-Range: bytes 21010-47021/47022
Content-Type 返回內容的MIME類型 Content-Type: text/html; charset=utf-8
Date 原始服務器消息發出的時間 Date: Tue, 15 Nov 2010 08:12:31 GMT
ETag 請求變量的實體標簽的當前值 ETag: “737060cd8c284d8af7ad3082f209582d”
Expires 響應過期的日期和時間 Expires: Thu, 01 Dec 2010 16:00:00 GMT
Last-Modified 請求資源的最后修改時間 Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT
Location 用來重定向接收方到非請求URL的位置來完成請求或標識新的資源 Location: https://www.baidu.com/
Pragma 包括實現特定的指令,它可應用到響應鏈上的任何接收方 Pragma: no-cache
Proxy-Authenticate 它指出認證方案和可應用到代理的該URL上的參數 Proxy-Authenticate: Basic
refresh 應用於重定向或一個新的資源被創造,在5秒之后重定向(由網景提出,被大部分瀏覽器支持) Refresh: 5; url=https://www.baidu.com/
Retry-After 如果實體暫時不可取,通知客戶端在指定時間之后再次嘗試 Retry-After: 120
Server web服務器軟件名稱 Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
Set-Cookie 設置Http Cookie Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
Trailer 指出頭域在分塊傳輸編碼的尾部存在 Trailer: Max-Forwards
Transfer-Encoding 文件傳輸編碼 Transfer-Encoding:chunked
Vary 告訴下游代理是使用緩存響應還是從原始服務器請求 Vary: *
Via 告知代理客戶端響應是通過哪里發送的 Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning 警告實體可能存在的問題 Warning: 199 Miscellaneous warning
WWW-Authenticate 表明客戶端請求實體應該使用的授權方案 WWW-Authenticate: Basic

注:HTTP部分內容來自 CSDN

Cookie 與 Session

Cookie 在客戶端的頭信息中,Session 在服務端存儲,文件、數據庫都可以
Session 通常需要 Cookie 的一個字段來對應用戶與 Session,所以當瀏覽器禁止 Cookie 時,Session將失效

測試框架 HttpClient

測試時需運行Mock 接口框架部分的startupWithCookies.json進行配合

演示代碼 Git 倉庫

//pom.xml 中添加 HttpClient依賴 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.1.3</version> </dependency> //HttpClient依賴的應用 @Test public void test1() throws IOException { //用來存放結果 String result; HttpGet get = new HttpGet("http://www.baidu.com"); //用來執行 GET 方法 HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); result = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println(result); } 

SprintBoot 自動化測試開發

演示代碼 Git 倉庫

/** * 開發一個需要攜帶參數才能訪問的 GET 請求 * 第一種實現方式:url: key=value&key=value * 以下模擬獲取商品列表 */ @RequestMapping(value = "/get/with/param",method = RequestMethod.GET) @ApiOperation(value = "需要攜帶參數才能訪問的 GET 請求一",httpMethod = "GET") public Map<String, Integer> getList(@RequestParam Integer start, @RequestParam Integer end){ Map<String, Integer> myList = new HashMap<>(); myList.put("鞋",400); myList.put("干脆面",1); myList.put("襯衫",300); return myList; } /** * 第二種需要攜帶參數訪問的 GET 請求 * url: ip:port/get/with/param/10/20 */ @RequestMapping(value = "/get/with/param/{start}/{end}") @ApiOperation(value = "需要攜帶參數才能訪問的 GET 請求二",httpMethod = "GET") public Map myGetList(@PathVariable Integer start, @PathVariable Integer end){ Map<String, Integer> myList = new HashMap<>(); myList.put("鞋",400); myList.put("干脆面",1); myList.put("襯衫",300); return myList; } 

插件:Lombok

若運行異常請首先打開Preferences > Build, Execution, Deployment > Compiler > Annotation Processors > Enable annotation processing,同時安裝應需要重啟 IDEA

Swagger訪問地址:http://localhost:8888/swagger-ui.html

在 Jmeter調試中顯示 Cookies 信息

# 找到對應Jmeter 的配置文件 # Mac 地址:/usr/local/Cellar/jmeter/5.0/libexec/bin/jmeter.properties # 修改如下內容 CookieManager.save.cookies=true 
Swagger 測試頁面

數據持久層框架 MyBatis

演示代碼 Git 倉庫

注意:yml 配置文件中冒號要加空格,否則會導致配置不生效

// 首先獲取一個執行 sql 語句的對象 @Autowired private SqlSessionTemplate template; @RequestMapping(value = "/getUserCount",method = RequestMethod.GET) @ApiOperation(value = "可以獲取到的用戶數",httpMethod = "GET") public int getUserCount(){ // getUserCount對應 mysql.xml 中的配置 return template.selectOne("getUserCount"); } @RequestMapping(value = "/addUser",method = RequestMethod.POST) public int addUser(@RequestBody User user){ return template.insert("addUser",user); } @RequestMapping(value = "/updateUser",method = RequestMethod.POST) public int updateUser(@RequestBody User user){ return template.update("updateUser",user); } @RequestMapping(value = "/deleteUser",method = RequestMethod.POST) public int delUser(@RequestParam int id){ return template.delete("deleteUser",id); } 

MyBatis+MySQL實現用例管理

完整代碼 Git 倉庫

# testng.xml
<?xml version="1.0" encoding="UTF-8" ?> <suite name="用戶管理系統測試套件"> <test name="用戶管理系統測試用例"> <classes> <class name="org.alanhou.cases.LoginTest"> <methods> <include name="loginTrue"/> <include name="loginFalse"/> </methods> </class> <class name="org.alanhou.cases.AddUserTest"> <methods> <include name="addUser"/> </methods> </class> <class name="org.alanhou.cases.GetUserInfoTest"> <methods> <include name="getUserInfo"/> </methods> </class> <class name="org.alanhou.cases.UpdateUserInfoTest"> <methods> <include name="updateUserInfo"/> <include name="deleteUser"/> </methods> </class> <class name="org.alanhou.cases.GetUserInfoListTest"> <methods> <include name="getUserListInfo"/> </methods> </class> </classes> </test> <listeners> <listener class-name="org.alanhou.config.ExtentTestNGIReporterListener"/> </listeners> </suite> 
MyBatis+MySQL實現用例管理

TestNG+MyBatis實現數據校驗

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> <configuration> <suiteXmlFiles> <suiteXmlFile> ./src/main/resources/testng.xml </suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> <!--Chapter13--> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>org.alanhou.Application</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <compilerArguments> <extdirs>${project.basedir}/libcd</extdirs> </compilerArguments> </configuration> </plugin> 

Jenkins持續集成

# 打包命令 mvn clean package wget https://mirrors.tuna.tsinghua.edu.cn/jenkins/war/latest/jenkins.war java -jar jenkins.war --httpPort=8080 # 后台啟動 nohup java -jar jenkins.war --httpPort=8080 & # 配置任務 deploy # 構建>Execute shell source /etc/profile pid=$(ps x | grep "Chapter13-1.0-SNAPSHOT.jar" | grep -v grep | awk '{print $1}') if [ -n "$pid"]; then kill -9 $pid fi cd Chapter13 mvn clean package cd target BUILD_ID=dontKillMe nohup java -jar Chapter13-1.0-SNAPSHOT.jar & # 構建后操作>Build other projects # 配置任務 test source /etc/profile cd Chapter12 mvn clean package result=$(curl -s http://127.0.0.1:8080/job/test/lastBuild/buildNumber --user admin001:123456) mkdir /home/apache-tomcat-9.0.7/webapps/ROOT/$result cp /root/.jenkins/workspace/test/Chapter12/test-output/index.html /home/apache-tomcat-9.0.7/webapps/ROOT/$result/index.html 
Jenkins 測試

在 Mac 本地安裝時,會出現This Jenkins instance appears to be offline.的報錯

解決方法:將 ~/.jenkins/hudson.model.UpdateCenter.xml文件中的 https 修改為 http 再重新執行上述安裝命令

安裝插件

Rebuilder, Safe Restart

擴展知識:

IDEA 快捷鍵

Option+j 快速導入包

Cmd+j 快速輸入,如 sout=System.out.println(); main導入

Option+Enter 代碼提示自動補全

Cmd+Option+O 移除未使用的包引用

刪除/移除了模塊后可通過 Cmd+;快捷鍵進入 Project Structure點擊+號來 Import Module

原文鏈接:Alan Hou 的個人博客



作者:矢寸心
鏈接:https://www.jianshu.com/p/1f357b849c87
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM