接口测试用例_接口自动化落地(一:MySQL+MyBatis实现对测试用例数据的读取)...

32faa9237d6b343f98ba5bb6d8bca502.gif 57dfad1bb004ea5048252c78c2863493.png

4b6f5d0ea227c989674fb6c20db0eafd.png

本文是为难得干货文章

(记得动手实践哦)

大家好,我是测试君,

下面分享一波JAVA接口自动化文章:

本篇文章讲解TestNG+MySQL+MyBatis+ExtentReports实现对测试用例数据的读取,下面放出所有配置文件的目录方便下文理解。 

29dd0bdc71ce8907e685330c2e9a2d74.png

1、配置mysql数据库

6c19908339f9aa445203c1adca88f59d.png

在这里,拿logincase表举例,后面也拿login做讲解。 a9321f1804cb835745577f09524f1c65.png

2、配置pom文件

pom文件部分

首先在pom文件中,配置httpclient、mybatis、mysql、extentreports、testng的各种依赖。

<?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.0modelVersion>  <groupId>com.course.codegroupId>  <artifactId>userInfoTestartifactId>  <version>1.0-SNAPSHOTversion>  <build>  <plugins>  <plugin>  <groupId>org.apache.maven.pluginsgroupId>  <artifactId>maven-compiler-pluginartifactId>  <configuration>  <source>6source>  <target>6target>  configuration>  plugin>  plugins>  build>  <dependencies>  <dependency>  <groupId>org.apache.httpcomponentsgroupId>  <artifactId>httpclientartifactId>  <version>4.1.2version>  dependency>  <dependency>  <groupId>org.jsongroupId>  <artifactId>jsonartifactId>  <version>20170516version>  dependency>  <dependency>  <groupId>org.mybatisgroupId>  <artifactId>mybatisartifactId>  <version>3.4.4version>  dependency>  <dependency>  <groupId>mysqlgroupId>  <artifactId>mysql-connector-javaartifactId>  <version>6.0.5version>  dependency>  <dependency>  <groupId>org.projectlombokgroupId>  <artifactId>lombokartifactId>  <version>1.16.16version>  dependency>  <dependency>  <groupId>com.relevantcodesgroupId>  <artifactId>extentreportsartifactId>  <version>2.41.1version>  dependency>  <dependency>  <groupId>com.vimalselvamgroupId>  <artifactId>testng-extentsreportartifactId>  <version>1.3.1version>  dependency>  <dependency>  <groupId>org.testnggroupId>  <artifactId>testngartifactId>  <version>6.11version>  dependency>  <dependency>  <groupId>com.aventstackgroupId>  <artifactId>extentreportsartifactId>  <version>3.0.6version>  dependency>  dependencies>

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" ?>  configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
        "http://mybatis.org/dtd/mybatis-3-config.dtd">  <configuration>    <environments default="development">  <environment id="development">  <transactionManager type="JDBC"/>  <dataSource type="POOLED">    <property name="driver" value="com.mysql.jdbc.Driver"/>    <property name="url" value="jdbc:mysql://localhost:3306/myBatisTest"/>    <property name="username" value="root"/>  <property name="password" value="123456"/>  dataSource>  environment>  environments>    <mappers>  <mapper resource="mapper/SQLMapper.xml"/>  mappers>  configuration>

5、配置testng.xml文件

testng.xml

resource目录下配置testng.xml文件,用以执行所有testng的测试套件。

<?xml  version="1.0" encoding="UTF-8" ?>  <suite name="用户管理系统测试套件">  <test name="用户管理系统测试用例">  <classes>  <class name="com.course.cases.loginTest">  <methods>  <include name="loginTrue"/>  <include name="loginFalse"/>  methods>  class>  <class name = "com.course.cases.AddUserTest">  <methods>  <include name="addUser"/>  methods>   class>  <class name = "com.course.cases.GetUserInfoTest">  <methods>  <include name="getUserInfo"/>  methods>  class>  <class name = "com.course.cases.GetUserListTest">  <methods>  <include name="getUserList"/>  methods>  class>  <class name = "com.course.cases.UpdateUserInfoTest">  <methods>  <include name="updateUserInfo"/>  <include name="deleteUser"/>  methods>  class>  classes>  test>  <listeners>  <listener class-name="com.course.config.ExtentTestNGIReporterListener"> listener>  listeners>  suite>

6、配置SQLMapper.xml文件

SQLMapper.xml

resources/mapper目录下,配置resources/mapper目录下,配置SQLMapper.xml文件,用户存储所有case的sql语句。文件,用户存储所有case的sql语句。

<?xml  version="1.0" encoding="UTF-8" ?>  mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  <mapper namespace="com.course.model">    <select id="loginCase" parameterType="Integer" resultType="com.course.model.LoginCase">  
        select * from loginCase  
        where id=#{id};  select>    <select id="addUserCase" parameterType="Integer" resultType="com.course.model.AddUserCase">  
        select * from addUserCase where id=#{id};  select>    <select id="getUserInfoCase" parameterType="Integer" resultType="com.course.model.GetUserInfoCase">  
        select * from getUserInfoCase where id=#{id};  select>    <select id="getUserListCase" parameterType="Integer" resultType="com.course.model.GetUserListCase">  
        select * from getUserListCase where id = #{id};  select>    <select id="updateUserInfoCase" parameterType="Integer" resultType="com.course.model.UpdateUserInfoCase">  
        select * from updateUserInfoCase where id = #{id};  select>  mapper>

7、配置model文件

com.course.model目录下,配置各个接口的数据配置文件,和一个InterfaceName枚举。 

f2ac1bcd657b4acc31fe6c13f4f1cd2d.png

在这里,同样拿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文件。 

67574e4fa12a0c4a9fe7e9161c2f426b.png

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()1:1;  
                }  
            });  
            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文件。 

a43424102ffa5bc09757b7b8406405eb.png

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类 

f9b42289afea98d307ab83bf43a4cd31.png

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。 

756ed06ea9f7ae2970094d615ec9028f.png

最后查看一下test-output目录下的index.xml文件,用浏览器打开可以看到ExtentReport的结果也生成成功。 

d0cd64613d6124227bcd657a057dd3dc.png

--------------------- 

作者:简单随风

来源:CSDN

原文链接:https://blog.csdn.net/lt326030434/article/details/80621268

bb459ba4a58cadcd00fc6fb0b7910845.png

c1875e06180ed0514ad2b76488a3be01.png

Android ADB命令大全

导入导出文件测试点

手把手带你入门git操作

05813349d50b57bfe9367413996fbcc9.png

还有一件重要的事情要和大家说,我不是经常看公众号后台,所以有时候大家在后台发留言,时间一旦超过2天,我就没有回复权限了。所以,我要公布自己的微信号了,欢迎大家来埋伏我?

320ce2407b1b4aa5fc93bcf2fe20de52.png

*本文创作:简单随风

*本文编辑:糖小幽

5e6d39a2bc14ba3376922dfc389f7348.png

记得收藏、转发哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值