接口自动化落地(一:MySQL+MyBatis实现对测试用例数据的读取)
本文是为难得干货文章
(记得动手实践哦)
大家好,我是测试君,
下面分享一波JAVA接口自动化文章:
本篇文章讲解TestNG+MySQL+MyBatis+ExtentReports实现对测试用例数据的读取,下面放出所有配置文件的目录方便下文理解。
1、配置mysql数据库
在这里,拿logincase表举例,后面也拿login做讲解。
2、配置pom文件
pom文件部分
首先在pom文件中,配置httpclient、mybatis、mysql、extentreports、testng的各种依赖。
<?xml version="1.0" encoding="UTF-8"?>
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">
4.0.0
com.course.code
userInfoTest
1.0-SNAPSHOT
org.apache.maven.plugins
maven-compiler-plugin
6
6
org.apache.httpcomponents
httpclient
4.1.2
org.json
json
20170516
org.mybatis
mybatis
3.4.4
mysql
mysql-connector-java
6.0.5
org.projectlombok
lombok
1.16.16
com.relevantcodes
extentreports
2.41.1
com.vimalselvam
testng-extentsreport
1.3.1
org.testng
testng
6.11
com.aventstack
extentreports
3.0.6
3、配置application.properties文件
application.properties
resource目录下配置application.properties文件,用以存储测试地址。
test.url=http://localhost:9529 #登录接口
login.uri=/v1/login
#更新用户信息
updateUserInfo.uri=/v1/updateUserInfo
#获取用户列表
getUserList.uri=/v1/getUserList
#获取用户信息
getUserInfo.uri=/v1/getUserInfo
#添加用户接口
addUser.uri=/v1/addUser
4、配置databaseConfig.xml文件
databaseConfig.xml
resource目录下配置databaseConfig.xml文件,用以连接数据库。
<?xml version="1.0" encoding="UTF-8" ?> /p>
"http://mybatis.org/dtd/mybatis-3-config.dtd">
5、配置testng.xml文件
testng.xml
resource目录下配置testng.xml文件,用以执行所有testng的测试套件。
6、配置SQLMapper.xml文件
SQLMapper.xml
resources/mapper目录下,配置resources/mapper目录下,配置SQLMapper.xml文件,用户存储所有case的sql语句。文件,用户存储所有case的sql语句。
<?xml version="1.0" encoding="UTF-8" ?> /p>
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
select * from loginCase
where id=#{id};
select * from addUserCase where id=#{id};
select * from getUserInfoCase where id=#{id};
select * from getUserListCase where id = #{id};
select * from updateUserInfoCase where id = #{id};
7、配置model文件
com.course.model目录下,配置各个接口的数据配置文件,和一个InterfaceName枚举。
在这里,同样拿LoginCase里的数据举例,其他case的格式一样。在这里参照mysql里配置的字段一一进行声明。
LoginCase
在这里,同样拿LoginCase里的数据举例,其他case的格式一样。在这里参照mysql里配置的字段一一进行声明。
@Data
public class LoginCase {
private int id;
private String userName;
private String password;
private String expected;
}
InterfaceName
InterfaceName配置如下
public enum InterfaceName {
GETUSERLIST,LOGIN,UPDATEUSERINFO,GETUSERINFO,ADDUSER
}
8、配置config文件
com.course.config目录下,新建ExtentTestNGIReporterListener文件和TestConfig文件。
ExtentTestNGIReporterListener
ExtentTestNGIReporterListener里是ExtentReport的测试报告配置文件,固定代码可以直接拷过去使用。
public class ExtentTestNGIReporterListener implements IReporter {
//生成的路径以及文件名
private static final String OUTPUT_FOLDER = "test-output/";
private static final String FILE_NAME = "index.html";
private ExtentReports extent;
@Override
public void generateReport(List xmlSuites, List suites, String outputDirectory) {
init();
boolean createSuiteNode = false;
if(suites.size()>1){
createSuiteNode=true;
}
for (ISuite suite : suites) {
Map 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 categoryList = extenttest.getModel().getCategoryContext().getAll();
categories = new String[categoryList.size()];
for(int index=0;index
categories[index] = categoryList.get(index).getName();
}
}
ExtentTest test;
if (tests.size() > 0) {
//调整用例排序,按时间排序
Set treeSet = new TreeSet(new Comparator() {
@Override
public int compare(ITestResult o1, ITestResult o2) {
return o1.getStartMillis()
}
});
treeSet.addAll(tests.getAllResults());
for (ITestResult result : treeSet) {
Object[] parameters = result.getParameters();
String name="";
//如果有参数,则使用参数的toString组合代替报告中的name
for(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 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()));
}
}
}
TestConfig
TestConfig内声明各个case的url和之后要用的一些变量。
public class TestConfig {
public static String loginUrl;
public static String updateUserInfoUrl;
public static String getUserListUrl;
public static String getUserInfoUrl;
public static String addUserUrl;
public static DefaultHttpClient defaultHttpClient;
public static CookieStore store;
}
9、配置utils文件
com.course.utils目录下配置ConfigFile文件和DatabaseUtil文件。
ConfigFile
ConfigFile内对各个case的url进行赋值
public class ConfigFile {
public static ResourceBundle bundle = ResourceBundle.getBundle("application",Locale.CHINA);
public static String getUrl(InterfaceName name){
String address = bundle.getString("test.url");
String uri = "";
//最终测试地址
String testUrl;
if (name == InterfaceName.GETUSERLIST){
uri = bundle.getString("getUserList.uri");
}
if (name == InterfaceName.LOGIN){
uri = bundle.getString("login.uri");
}
if (name == InterfaceName.UPDATEUSERINFO){
uri = bundle.getString("updateUserInfo.uri");
}
if (name == InterfaceName.GETUSERINFO){
uri = bundle.getString("getUserInfo.uri");
}
if (name == InterfaceName.ADDUSER){
uri = bundle.getString("addUser.uri");
}
testUrl = address + uri;
return testUrl;
}
}
DatabaseUtil
DatabaseUtil内配置一个getSqlsession方法,作用是执行配置文件中的sql语句,用以之后每个case可以直接调用而不用重复的写这一部分代码。
public class DatabaseUtil {
public static SqlSession getSqlsession() throws IOException {
//获取配置资源文件
Reader reader = Resources.getResourceAsReader("databaseConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
//sqlSession就是能够执行配置文件中的sql语句
SqlSession sqlSession=factory.openSession();
return sqlSession;
}
}
10、配置cases文件
com.course.cases目录下配置所有case类
loginTest
在这里也只拿loginTest进行举例
public class loginTest {
@BeforeTest(groups="loginTrue",description = "测试准备工作,获取httpClient对象")
public void beforeTest(){
TestConfig.getUserInfoUrl = ConfigFile.getUrl(InterfaceName.GETUSERINFO);
TestConfig.getUserListUrl = ConfigFile.getUrl(InterfaceName.GETUSERLIST);
TestConfig.addUserUrl = ConfigFile.getUrl(InterfaceName.ADDUSER);
TestConfig.loginUrl = ConfigFile.getUrl(InterfaceName.LOGIN);
TestConfig.updateUserInfoUrl = ConfigFile.getUrl(InterfaceName.UPDATEUSERINFO);
TestConfig.defaultHttpClient = new DefaultHttpClient();
}
@Test(groups = "loginTrue",description = "用户登录接口测试")
public void loginTrue() throws IOException {
SqlSession session = DatabaseUtil.getSqlsession();
LoginCase loginCase = session.selectOne("loginCase",1);
System.out.println(loginCase.toString());
System.out.println(TestConfig.loginUrl);
}
@Test(description = "用户登录失败接口测试")
public void loginFalse() throws IOException {
SqlSession session = DatabaseUtil.getSqlsession();
LoginCase loginCase = session.selectOne("loginCase",2);
System.out.println(loginCase.toString());
System.out.println(TestConfig.loginUrl);
}
}
到这里,一套完整的从mysql读取测试用例数据到存储在java工程内的配置就写完了
我们可以执行一下testng.xml文件,可以看到所有case都执行成功,并且在控制台上打印出了所有数据信息以及每个case的url。
最后查看一下test-output目录下的index.xml文件,用浏览器打开可以看到ExtentReport的结果也生成成功。
Android ADB命令大全
导入导出文件测试点
手把手带你入门git操作
还有一件重要的事情要和大家说,我不是经常看公众号后台,所以有时候大家在后台发留言,时间一旦超过2天,我就没有回复权限了。所以,我要公布自己的微信号了,欢迎大家来埋伏我
本文创作:简单随风本文编辑:糖小幽
记得收藏、转发哦!