转载:http://www.jianshu.com/p/6249f9a9e9c4

  什么是Cucumber?什么是BDD?这里不细讲,不懂的直接查看官方:https://cucumber.io/
  什么是Rest Assured?传送门:https://github.com/rest-assured/rest-assured

  以下以java为开发语言,快速搭建一个cucumber+Rest Assured的api自动化测试平台。
  1. 用IDEA 新建一个Maven工程,并pom文件添加如下配置:

        <!--ccucumber 相关依赖-->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java8</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.4</version>
</dependency> <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-html -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-html</artifactId>
<version>0.2.3</version>
</dependency> <!--rest-assured 接口测试框架-->
<!-- https://mvnrepository.com/artifact/com.jayway.restassured/rest-assured -->
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.9.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.10</version>
</dependency> <!--log 引入-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>provided</scope>
</dependency> <!--compare jsoon-->
<dependency>
<groupId>net.javacrumbs.json-unit</groupId>
<artifactId>json-unit</artifactId>
<version>1.13.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
  1. 新建个ApiTools类,并对Rest Assured进程二次封装,主要是Post 和 Get请求的基础封装和对返回json解析的封装,具体代码如下:

    /**
    * 带json的post请求
    *
    * @param apiPath api地址
    * @param json 请求json
    * @return api返回的Response
    */
    public static Response post(String apiPath, String json) {
    // 开始发起post 请求
    String path = Parameters.BOSEHOST + apiPath;
    Response response = given().
    contentType("application/json;charset=UTF-8").
    headers("header1", "value1").
    cookies("cookies1", "value1").
    body(json).
    when().log().all().post(path.trim());
    log.info(response.statusCode());
    log.info("reponse:");
    response.getBody().prettyPrint();
    return response;
    } /**
    * get 请求
    *
    * @param apiPath api路径
    * @return api的response
    */
    public static Response get(String apiPath) {
    // 开始发起GET 请求
    String path = Parameters.BOSEHOST + apiPath;
    Response response = given().
    contentType("application/json;charset=UTF-8").
    headers("headers1", "value1").
    cookie("cookie1", "value1").
    when().log().all().get(path.trim());
    log.info(response.statusCode());
    log.info("reponse:");
    response.getBody().prettyPrint();
    return response;
    } /**
    * 获取json中某个key值
    * @param response 接口返回
    * @param jsonPath jsonpath, 例如 a.b.c a.b[1].c a
    * @return
    */
    public static String getJsonPathValue(Response response, String jsonPath) {
    String reponseJson = String.valueOf(response.jsonPath().get(jsonPath));
    // String jsonValue = String.valueOf(from(reponseJson).get(jsonPath));
    return reponseJson;
    }

    3.新建个Steps 类,完成常用step的封装,具体代码如下:

    import com.jayway.restassured.response.Response;
    import com.tools.apitools.ApiTools;
    import com.tools.apitools.MyAssert;
    import com.tools.filetools.ReadTxtFile;
    import cucumber.api.java.en.Then;
    import cucumber.api.java.en.When;
    import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
    /**
    * Created by MeYoung on 8/1/2016.
    * <p>
    * Steps 集合
    */
    public class Steps { Response response = null; @When("^I send a GET request to \"(.*?)\"$")
    public void getRequest(String path) {
    response = ApiTools.get(path);
    } @When("^I send a POST request to \"(.*?)\"$")
    public void postRequest(String apiPath) throws Throwable {
    response = ApiTools.post(apiPath);
    } @When("^I send a POST request to \"(.*?)\" and request json:$")
    public void postRequestWithJson(String apiPath, String json) {
    response = ApiTools.post(apiPath, json);
    } @When("^I use a \"(.*?)\" file to send a POST request to \"(.*?)\"$")
    public void postRequestWihtFile(String fileName, String path) {
    String json = ReadTxtFile.readTxtFile(fileName);
    response = ApiTools.post(path, json);
    } @Then("^the JSON response equals$")
    public void assertResponseJson(String expected) {
    String responseJson = response.body().asString();
    assertJsonEquals(responseJson, expected);
    } @Then("^the JSON response equals json file \"(.*?)\"$")
    public void theJSONResponseEqualsJsonFile(String fileName) {
    String responseJson = response.body().asString();
    String fileJson = ReadTxtFile.readTxtFile(fileName);
    assertJsonEquals(responseJson, fileJson);
    } @Then("^the response status should be \"(\\d{3})\"$")
    public void assertStatusCode(int statusCode) {
    Object jsonResponse = response.getStatusCode();
    MyAssert.assertEquals(jsonResponse, statusCode);
    } @Then("^the JSON response \"(.*?)\" equals \"(.*?)\"$")
    public void assertEquals(String str, String expected) {
    String jsonValue = ApiTools.getJsonPathValue(response, str);
    MyAssert.assertEquals(jsonValue, expected);
    } @Then("^the JSON response \"(.*?)\" type should be \"(.*?)\"$")
    public void assertMatch(String str, String match) {
    String jsonValue = ApiTools.getJsonPathValue(response, str);
    MyAssert.assertMatch(jsonValue, match);
    } @Then("^the JSON response \"(.*?)\" should be not null$")
    public void assertNotNull(String str) {
    String jsonValue = ApiTools.getJsonPathValue(response, str);
    MyAssert.assertNotNull(jsonValue);
    } @Then("^the JSON response \"(.*?)\" start with \"(.*?)\"$")
    public void assertStartWith(String str, String start) {
    String jsonValue = ApiTools.getJsonPathValue(response, str);
    MyAssert.assertStartWith(jsonValue, start);
    }
    @Then("^the JSON response \"(.*?)\" end with \"(.*?)\"$")
    public void assertEndWith(String str, String end) {
    String jsonValue = ApiTools.getJsonPathValue(response, str);
    MyAssert.assertEndWith(jsonValue, end);
    }
    @Then("^the JSON response \"(.*?)\" include \"(.*?)\"$")
    public void assertInclude(String str, String include) {
    String jsonValue = ApiTools.getJsonPathValue(response, str);
    MyAssert.assertInclude(jsonValue, include);
    }
    }

      当然上面代码还涉及到一些Asssert的封装,这里就不列出来,个人喜好不同,更具自己熟悉的情况去引入自己熟悉的jar包。

  ok,最后我们愉快的写两个case,看看效果:

  @get
Scenario Outline: use examples
When I send a GET request to "apiurl"
Then the response status should be "200"
Then the JSON response "<jsonPath>" equals "<value>"
Examples:
| jsonPath | value |
| genericPlan | false |
| ehiCarrierId | 90121100 |
| carrierName | Anthem Blue Cross | @post
Scenario: test post request
When I send a POST request to "apiurl"
Then the response status should be "200"
And the JSON response "message" equals "success"
# 校验放回值是否是某种类型
And the JSON response "sessionId" type should be "^\d{6}$"
# 校验返回值不为空
And the JSON response "url" should be not null
# 校验是否以XX开头
Then the JSON response "message" start with "su"
# 校验是否以XX开头
Then the JSON response "message" end with "ss"
# 校验是否以XX开头
Then the JSON response "message" include "ss"
# 校验返回json是否为XXX,对整个返回json的校验
Then the JSON response equals
"""
{
"result":"success"
}
"""

通过Junit 运行feature.

  1. 在Pom.xml 文件添加junit相关包:

         <dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.4</version>
    <scope>test</scope>
    </dependency> <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
    </dependency>
  2. 在feature 同级目录下新建个运行类,代码例子如下:
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith; @RunWith(Cucumber.class)
@CucumberOptions(
strict = true,
monochrome = true,
plugin = {"pretty", "html:target/cucumber", "json:target/cucumber.json"},
features = {"src/test/java/bosev2"},
glue = {"com.bose.step"},
tags = {"~@unimplemented"})
public class RunnerBoseTest {
}

@RunWith(Cucumber.class) : 注解表示通过Cucumber的Junit 方式运行脚本
@CucumberOptions () :注解用于配置运行信息,其中代码中的plugin 表示测试报告输出的路径和格式, feature 表示被运行的feature文件的包路径, glue中配置steps的包路径地址,tags中配置要运行的用例的tags名,其实~符号表示除了这个tags的所有tags.

通过Jenkins 执行

  1. 在Pom.xml 文件里面添加运行插件,如下:

    <build>
    <plugins>
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <inherited>true</inherited>
    <configuration>
    <source>1.7</source>
    <target>1.7</target>
    <encoding>UTF-8</encoding>
    </configuration>
    </plugin> <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
    <reuseForks>false</reuseForks>
    </configuration>
    </plugin>
    </plugins>
    </build>
  2. 在Jenkins 中添加Cucumber-JVM reports插件。
  3. 新建Maven job,配置maven构建方式和构建后的测试报告展示。

Paste_Image.png

Cucumber-JVM reports 提供了非常漂亮的report,如下:

Paste_Image.png

最后附上项目地址:https://github.com/MeYoung/cucumber_restassured

作者:米阳MeYoung
链接:http://www.jianshu.com/p/6249f9a9e9c4
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

参考:https://github.com/jenkinsci/cucumber-reports-plugin

Cucumber+Rest Assured快速搭建api自动化测试平台的更多相关文章

  1. 使用HttpReports快速搭建API分析平台

    HttpReports 简单介绍 HttpReports 是 .Net Core下的一个Web组件,适用于 WebAPI 项目和 API 网关项目,通过中间件的形式集成到您的项目中, 通过HttpRe ...

  2. flask + Python3 实现的的API自动化测试平台---- IAPTest接口测试平台(总结感悟篇)

    前言: 在前进中去发现自己的不足,在学习中去丰富自己的能力,在放弃时想想自己最初的目的,在困难面前想想怎么踏过去.在不断成长中去磨炼自己. 正文: 时间轴 flask + Python3 实现的的AP ...

  3. Docker: 快速搭建LNMP网站平台

    快速搭建LNMP网站平台 步骤: 1.自定义网络(这里建立一个自定义网络,名字叫 lnmp, 让LNMP网站的服务,都加入这个自定义网络)docker network create lnmp2.创建M ...

  4. Linux下搭建接口自动化测试平台

    前言 我们今天来学习一下在Linux下如何搭建基于HttpRunner开发的接口自动化测试平台吧! 需要在Linux上提前准备的环境(下面是本人搭建时的环境): 1,Python 3.6.8 (可参考 ...

  5. Log4net快速配置使用指南。(快速搭建log4net日志平台手册)

    每做一个新项目,都会用到log4net,但总是忘记如何快速配置.有时在网上搜半天也找不到好的模板,大都在介绍参数的使用,在此做下总结,争取下次用时仅10分钟就可搭建好log4net. 直接上介绍的步骤 ...

  6. 小白入门AI教程:教你快速搭建大数据平台『Hadoop+Spark』

    Apache Spark 简介 Apache Spark 是专为大规模数据处理而设计的快速通用的计算引擎.Spark是UC Berkeley AMP lab (加州大学伯克利分校的AMP实验室)所开源 ...

  7. vue.js快速搭建图书管理平台

      前  言 上一期简单讲解了vue的基本语法,这一次我们做一个小项目,搭建一个简单的图书管理平台,能够让我们更深刻的理解这门语言的妙用.   1.DEMO样式 首先我们需要搭建一个简单的demo样式 ...

  8. flask + Python3 实现的的API自动化测试平台---- IAPTest接口测试平台

    **背景: 1.平时测试接口,总是现写代码,对测试用例的管理,以及测试报告的管理持久化做的不够,              2.工作中移动端开发和后端开发总是不能并行进行,需要一个mock的依赖来让他 ...

  9. 资深程序员教你如何实现API自动化测试平台!附项目源码!

    原文链接: 1.平时测试接口,总是现写代码,对测试用例的管理,以及测试报告的管理持久化做的不够, 2.工作中移动端开发和后端开发总是不能并行进行,需要一个mock的依赖来让他们并行开发. 3.同时让自 ...

随机推荐

  1. 大数据学习——sparkRDD

    https://www.cnblogs.com/qingyunzong/p/8899715.html 练习1:map.filter //通过并行化生成rdd val rdd1 = sc.paralle ...

  2. 元类相关(type & metaclass)

    metaclass作用: 1) 拦截类的创建 2) 修改类 3) 返回修改之后的类 """为什么要用metaclass类而不是函数? 由于__metaclass__可以接 ...

  3. SpriteKit-SKView

    1.暂停这个视图 @property (nonatomic, getter = isPaused) BOOL paused; 2.视图性能的一些参数 @property (nonatomic) BOO ...

  4. 漫谈登录桩(MockStub)的实现

    2014年6月4日,6月的第一个星期三,我正式入职百度,开始baiduer的工作.这不到2个月的时间,因为人力资源这边原因,我从INF部门离开,拉到了百度Hi-Server团队中来.2个完全不着调的岗 ...

  5. ubuntu 安装tomcat<服务器>

    一.下载tomcat 可以先下载到本地,然后ftp到服务器 官方 Apache Tomcat 的下载页面(下面的链接是apache自己的镜像服务器的地址,不同网络连接的话,apache会给出不同的镜像 ...

  6. 解决 Could not load hsdis-amd64.dll

    win10下想查看JIT编译的汇编源码 结果提示: Could not load hsdis-amd64.dll; library not loadable; PrintAssembly is dis ...

  7. PHP中的验证码类(完善验证码)

    运行结果: <!--vcode.class.php--> <?php class Vcode { private $width; //宽 private $height; //高 p ...

  8. fullpage在vue单页面当中使用会出现的问题以及解决办法

    在 vue 单页面当中发现fullpage会报错,报错信息大概意思为,fullpage不允许初始化多次. 解决办法,在使用fullpage的组件跳转路由进入销毁组件之前的生命周期的时候对fullpag ...

  9. MockMvc详解

    ★  MockMvc - SpringMVC单元测试的独立测试: 一.简介 为何使用MockMvc?         对模块进行集成测试时,希望能够通过输入URL对Controller进行测试,如果通 ...

  10. LeetCode OJ--Longest Consecutive Sequence ***

    http://oj.leetcode.com/problems/longest-consecutive-sequence/ 起初想的是排序,查了下O(n)的排序算法有计数排序.基数排序.桶排序.后来考 ...