Java接口自动化测试实战笔记
- 综述
- 代码管理工具Git
- 测试框架 TestNG
- 测试报告
- Mock 接口框架
- HTTP 协议接口
- 测试框架 HttpClient
- SprintBoot 自动化测试开发
- 数据持久层框架 MyBatis</a
- MyBatis+MySQL实现用例管理
- TestNG+MyBatis实现数据校验
- Jenkins持续集成
综述
- 需求阶段:项目立项、产品设计、需求文档
- 研发阶段: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
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
测试框架 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>
执行顺序
<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
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) //单位为毫秒
测试报告
推荐: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 需FQ才能加载
<!--<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);
Mock 接口框架
演示代码 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 添加重定向信息
HTTP 协议接口
Requests Header (请求头)
Responses Header(响应头)
注: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);
}
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;">/**
- 开发一个需要携带参数才能访问的 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
数据持久层框架 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);
}
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>
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;"><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
在 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/