虽然我写了这文章,但是我不建议这种做法,原因很简单,这是把简单事情复杂化。

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

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

  1. <!--ccucumber 相关依赖-->
  2. <dependency>
  3. <groupId>info.cukes</groupId>
  4. <artifactId>cucumber-java8</artifactId>
  5. <version>1.2.4</version>
  6. <scope>test</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>info.cukes</groupId>
  10. <artifactId>cucumber-java</artifactId>
  11. <version>1.2.4</version>
  12. </dependency>
  13. <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-html -->
  14. <dependency>
  15. <groupId>info.cukes</groupId>
  16. <artifactId>cucumber-html</artifactId>
  17. <version>0.2.3</version>
  18. </dependency>
  19. <!--rest-assured 接口测试框架-->
  20. <!-- https://mvnrepository.com/artifact/com.jayway.restassured/rest-assured -->
  21. <dependency>
  22. <groupId>com.jayway.restassured</groupId>
  23. <artifactId>rest-assured</artifactId>
  24. <version>2.9.0</version>
  25. </dependency>
  26. <!-- https://mvnrepository.com/artifact/org.testng/testng -->
  27. <dependency>
  28. <groupId>org.testng</groupId>
  29. <artifactId>testng</artifactId>
  30. <version>6.9.10</version>
  31. </dependency>
  32. <!--log 引入-->
  33. <dependency>
  34. <groupId>log4j</groupId>
  35. <artifactId>log4j</artifactId>
  36. <version>1.2.17</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.slf4j</groupId>
  40. <artifactId>slf4j-log4j12</artifactId>
  41. <version>1.7.5</version>
  42. <scope>provided</scope>
  43. </dependency>
  44. <!--compare jsoon-->
  45. <dependency>
  46. <groupId>net.javacrumbs.json-unit</groupId>
  47. <artifactId>json-unit</artifactId>
  48. <version>1.13.0</version>
  49. </dependency>
  50. <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
  51. <dependency>
  52. <groupId>com.fasterxml.jackson.core</groupId>
  53. <artifactId>jackson-databind</artifactId>
  54. <version>2.8.1</version>
  55. </dependency>
  1. 新建个ApiTools类,并对Rest Assured进程二次封装,主要是Post 和 Get请求的基础封装和对返回json解析的封装,具体代码如下:
  1. /**
  2. * 带json的post请求
  3. *
  4. * @param apiPath api地址
  5. * @param json 请求json
  6. * @return api返回的Response
  7. */
  8. public static Response post(String apiPath, String json) {
  9. // 开始发起post 请求
  10. String path = Parameters.BOSEHOST + apiPath;
  11. Response response = given().
  12. contentType("application/json;charset=UTF-8").
  13. headers("header1", "value1").
  14. cookies("cookies1", "value1").
  15. body(json).
  16. when().log().all().post(path.trim());
  17. log.info(response.statusCode());
  18. log.info("reponse:");
  19. response.getBody().prettyPrint();
  20. return response;
  21. }
  22. /**
  23. * get 请求
  24. *
  25. * @param apiPath api路径
  26. * @return api的response
  27. */
  28. public static Response get(String apiPath) {
  29. // 开始发起GET 请求
  30. String path = Parameters.BOSEHOST + apiPath;
  31. Response response = given().
  32. contentType("application/json;charset=UTF-8").
  33. headers("headers1", "value1").
  34. cookie("cookie1", "value1").
  35. when().log().all().get(path.trim());
  36. log.info(response.statusCode());
  37. log.info("reponse:");
  38. response.getBody().prettyPrint();
  39. return response;
  40. }
  41. /**
  42. * 获取json中某个key值
  43. * @param response 接口返回
  44. * @param jsonPath jsonpath, 例如 a.b.c a.b[1].c a
  45. * @return
  46. */
  47. public static String getJsonPathValue(Response response, String jsonPath) {
  48. String reponseJson = String.valueOf(response.jsonPath().get(jsonPath));
  49. // String jsonValue = String.valueOf(from(reponseJson).get(jsonPath));
  50. return reponseJson;
  51. }

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

  1. import com.jayway.restassured.response.Response;
  2. import com.tools.apitools.ApiTools;
  3. import com.tools.apitools.MyAssert;
  4. import com.tools.filetools.ReadTxtFile;
  5. import cucumber.api.java.en.Then;
  6. import cucumber.api.java.en.When;
  7. import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
  8. /**
  9. * Created by MeYoung on 8/1/2016.
  10. * <p>
  11. * Steps 集合
  12. */
  13. public class Steps {
  14. Response response = null;
  15. @When("^I send a GET request to \"(.*?)\"$")
  16. public void getRequest(String path) {
  17. response = ApiTools.get(path);
  18. }
  19. @When("^I send a POST request to \"(.*?)\"$")
  20. public void postRequest(String apiPath) throws Throwable {
  21. response = ApiTools.post(apiPath);
  22. }
  23. @When("^I send a POST request to \"(.*?)\" and request json:$")
  24. public void postRequestWithJson(String apiPath, String json) {
  25. response = ApiTools.post(apiPath, json);
  26. }
  27. @When("^I use a \"(.*?)\" file to send a POST request to \"(.*?)\"$")
  28. public void postRequestWihtFile(String fileName, String path) {
  29. String json = ReadTxtFile.readTxtFile(fileName);
  30. response = ApiTools.post(path, json);
  31. }
  32. @Then("^the JSON response equals$")
  33. public void assertResponseJson(String expected) {
  34. String responseJson = response.body().asString();
  35. assertJsonEquals(responseJson, expected);
  36. }
  37. @Then("^the JSON response equals json file \"(.*?)\"$")
  38. public void theJSONResponseEqualsJsonFile(String fileName) {
  39. String responseJson = response.body().asString();
  40. String fileJson = ReadTxtFile.readTxtFile(fileName);
  41. assertJsonEquals(responseJson, fileJson);
  42. }
  43. @Then("^the response status should be \"(\\d{3})\"$")
  44. public void assertStatusCode(int statusCode) {
  45. Object jsonResponse = response.getStatusCode();
  46. MyAssert.assertEquals(jsonResponse, statusCode);
  47. }
  48. @Then("^the JSON response \"(.*?)\" equals \"(.*?)\"$")
  49. public void assertEquals(String str, String expected) {
  50. String jsonValue = ApiTools.getJsonPathValue(response, str);
  51. MyAssert.assertEquals(jsonValue, expected);
  52. }
  53. @Then("^the JSON response \"(.*?)\" type should be \"(.*?)\"$")
  54. public void assertMatch(String str, String match) {
  55. String jsonValue = ApiTools.getJsonPathValue(response, str);
  56. MyAssert.assertMatch(jsonValue, match);
  57. }
  58. @Then("^the JSON response \"(.*?)\" should be not null$")
  59. public void assertNotNull(String str) {
  60. String jsonValue = ApiTools.getJsonPathValue(response, str);
  61. MyAssert.assertNotNull(jsonValue);
  62. }
  63. @Then("^the JSON response \"(.*?)\" start with \"(.*?)\"$")
  64. public void assertStartWith(String str, String start) {
  65. String jsonValue = ApiTools.getJsonPathValue(response, str);
  66. MyAssert.assertStartWith(jsonValue, start);
  67. }
  68. @Then("^the JSON response \"(.*?)\" end with \"(.*?)\"$")
  69. public void assertEndWith(String str, String end) {
  70. String jsonValue = ApiTools.getJsonPathValue(response, str);
  71. MyAssert.assertEndWith(jsonValue, end);
  72. }
  73. @Then("^the JSON response \"(.*?)\" include \"(.*?)\"$")
  74. public void assertInclude(String str, String include) {
  75. String jsonValue = ApiTools.getJsonPathValue(response, str);
  76. MyAssert.assertInclude(jsonValue, include);
  77. }
  78. }

当然上面代码还涉及到一些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>
  1. 在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>
  1. 在Jenkins 中添加Cucumber-JVM reports插件。
  2. 新建Maven job,配置maven构建方式和构建后的测试报告展示。

24-1-Cucumber Rest-Assured快速搭建api自动化测试平台 - 图1

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

24-1-Cucumber Rest-Assured快速搭建api自动化测试平台 - 图2

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