Java接口自动化测试实战笔记

Java接口自动化测试实战笔记

综述

  • 需求阶段:项目立项、产品设计、需求文档
  • 研发阶段:UI 设计、前端开发、后端开发、测试设计、测试开发(并行)
  • 测试阶段:环境搭建、多项测试执行、BUG 修复、测试报告
  • 项目上线:线上回归测试、上线报告、添加监控

接口测试范围:

功能测试:等价类划分法、边界值分析法、错误推断法、因果图法、判定表驱动法、正交试验法、功能图法、场景法

异常测试:数据异常(null,””,数据类型)、环境异常(负载均衡架构、冷热备份)

性能测试(狭义):负载测试、压力测试或强度测试、并发测试、稳定性测试或可靠性测试

手工接口测试的常用工具

  • Postman
  • HttpRequest(Firefox 插件)
  • Fiddler(具备抓包和发送请求功能)
  • 半自动化:Jmeter(结果统计方面不完善)

自动化框架的设计

  • 显示层:测试报告
  • 控制层:逻辑验证
  • 持久层:测试用例存储(数据驱动)

测试代码:https://github.com/alanhou7/AutoTest

代码管理工具Git

安装客户端

    <div id="crayon-5d7709084fec5672951318" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">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









1
2
3
4
5
6
7
8
9
10
11
12
13
14

yum install -y git # Linux
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命令

    <div id="crayon-5d7709084fece402475172" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;"># 克隆项目到本地

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









1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

# 克隆项目到本地
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 仓库

    <div id="crayon-5d7709084fed1104162352" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;"># pom.xml

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









1
2
3
4
5
6
7
8
9

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


执行顺序

    <div id="crayon-5d7709084fed4024131228" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">//最基本的注解,用来把方法标记为测试的一部分

@Test

//BeforeMethod 是在测试方法之前运行的
@BeforeMethod
//AfterMethod 是在测试方法之后运行的
@AfterMethod

//BeforeClass 是在类之前运行的方法
@BeforeClass
//AfterClass 是在类之后运行的方法
@AfterClass

//BeforeSuite测试套件在BeforeClass之前运行
@BeforeSuite
//AfterSuite测试套件在AfterClass之后运行
@AfterSuite








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

//最基本的注解,用来把方法标记为测试的一部分
@Test
 
//BeforeMethod 是在测试方法之前运行的
@BeforeMethod
//AfterMethod 是在测试方法之后运行的
@AfterMethod
 
//BeforeClass 是在类之前运行的方法
@BeforeClass
//AfterClass 是在类之后运行的方法
@AfterClass
 
//BeforeSuite测试套件在BeforeClass之前运行
@BeforeSuite
//AfterSuite测试套件在AfterClass之后运行
@AfterSuite


BeforeMethod和AfterMethod 会在类中的每个@Test 装饰的方法之前和之后运行

    <div id="crayon-5d7709084fed7487804124" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">//忽略测试

@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) //单位为毫秒








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

//忽略测试
@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 仓库

    <div id="crayon-5d7709084fed9195902050" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">//默认的监听器生成的报告 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);








1
2
3
4
5
6
7

//默认的监听器生成的报告 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" />
 
htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);


Java接口自动化测试实战笔记

Mock 接口框架

Moco 框架

演示代码 Git 仓库

    <div id="crayon-5d7709084fedc268093409" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">// 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 添加重定向信息








1
2
3
4
5
6
7
8
9
10
11
12

// 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 添加重定向信息


Java接口自动化测试实战笔记

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: http://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 仓库

    <div id="crayon-5d7709084fedf820205067" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">//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);
}








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

//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 仓库

    <div id="crayon-5d7709084fee2924527994" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">/**

@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;

}

/**

@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;

}








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

/
* 开发一个需要携带参数才能访问的 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 信息

    <div id="crayon-5d7709084fee5200187582" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;"># 找到对应Jmeter 的配置文件

Mac 地址:/usr/local/Cellar/jmeter/5.0/libexec/bin/jmeter.properties

修改如下内容

CookieManager.save.cookies=true








1
2
3
4

# 找到对应Jmeter 的配置文件
# Mac 地址:/usr/local/Cellar/jmeter/5.0/libexec/bin/jmeter.properties
# 修改如下内容
CookieManager.save.cookies=true


Java接口自动化测试实战笔记

数据持久层框架 MyBatis

演示代码 Git 仓库

注意:yml 配置文件中冒号要加空格,否则会导致配置不生效

    <div id="crayon-5d7709084fee7524761403" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">// 首先获取一个执行 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);
}








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

// 首先获取一个执行 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 仓库

    <div id="crayon-5d7709084feea270557906" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;"># 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>








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

# 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>


Java接口自动化测试实战笔记

TestNG+MyBatis实现数据校验

    <div id="crayon-5d7709084feec647763140" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;">&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
&lt;version&gt;2.22.1&lt;/version&gt;
&lt;configuration&gt;
    &lt;suiteXmlFiles&gt;
        &lt;suiteXmlFile&gt;
            ./src/main/resources/testng.xml
        &lt;/suiteXmlFile&gt;
    &lt;/suiteXmlFiles&gt;
&lt;/configuration&gt;

</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>








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

<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持续集成

    <div id="crayon-5d7709084feef988474187" class="crayon-syntax crayon-theme-sublime-text crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-mouseover" style="margin-top: 12px; margin-bottom: 12px; font-size: 12px !important; line-height: 15px !important; height: auto;">
    
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 12px !important; line-height: 15px !important; z-index: 0; opacity: 0; overflow: hidden;"># 打包命令

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








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

# 打包命令
mvn clean package
 
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


Java接口自动化测试实战笔记

在 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

原文地址:https://alanhou.org/java-automated-testing/
【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/jpfss/p/11495970.html