雖然我寫(xiě)了這文章汰寓,但是我不建議這種做法,原因很簡(jiǎn)單苹粟,這是把簡(jiǎn)單事情復(fù)雜化有滑。
什么是Cucumber?什么是BDD嵌削?這里不細(xì)講毛好,不懂的直接查看官方:https://cucumber.io/
什么是Rest Assured?傳送門(mén):https://github.com/rest-assured/rest-assured
以下以java為開(kāi)發(fā)語(yǔ)言掷贾,快速搭建一個(gè)cucumber+Rest Assured的api自動(dòng)化測(cè)試平臺(tái)。
1. 用IDEA 新建一個(gè)Maven工程荣茫,并pom文件添加如下配置:
<!--ccucumber 相關(guān)依賴(lài)-->
<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 接口測(cè)試框架-->
<!-- 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>
- 新建個(gè)ApiTools類(lèi)想帅,并對(duì)Rest Assured進(jìn)程二次封裝,主要是Post 和 Get請(qǐng)求的基礎(chǔ)封裝和對(duì)返回json解析的封裝啡莉,具體代碼如下:
/**
* 帶json的post請(qǐng)求
*
* @param apiPath api地址
* @param json 請(qǐng)求json
* @return api返回的Response
*/
public static Response post(String apiPath, String json) {
// 開(kāi)始發(fā)起post 請(qǐng)求
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 請(qǐng)求
*
* @param apiPath api路徑
* @return api的response
*/
public static Response get(String apiPath) {
// 開(kāi)始發(fā)起GET 請(qǐng)求
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中某個(gè)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.新建個(gè)Steps 類(lèi)港准,完成常用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);
}
}
當(dāng)然上面代碼還涉及到一些Asssert的封裝咧欣,這里就不列出來(lái)浅缸,個(gè)人喜好不同,更具自己熟悉的情況去引入自己熟悉的jar包魄咕。
ok衩椒,最后我們愉快的寫(xiě)兩個(gè)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"
# 校驗(yàn)放回值是否是某種類(lèi)型
And the JSON response "sessionId" type should be "^\d{6}$"
# 校驗(yàn)返回值不為空
And the JSON response "url" should be not null
# 校驗(yàn)是否以XX開(kāi)頭
Then the JSON response "message" start with "su"
# 校驗(yàn)是否以XX開(kāi)頭
Then the JSON response "message" end with "ss"
# 校驗(yàn)是否以XX開(kāi)頭
Then the JSON response "message" include "ss"
# 校驗(yàn)返回json是否為XXX,對(duì)整個(gè)返回json的校驗(yàn)
Then the JSON response equals
"""
{
"result":"success"
}
"""
通過(guò)Junit 運(yùn)行feature.
- 在Pom.xml 文件添加junit相關(guān)包:
<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>
- 在feature 同級(jí)目錄下新建個(gè)運(yùn)行類(lèi)毛萌,代碼例子如下:
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) : 注解表示通過(guò)Cucumber的Junit 方式運(yùn)行腳本
@CucumberOptions () :注解用于配置運(yùn)行信息苟弛,其中代碼中的plugin 表示測(cè)試報(bào)告輸出的路徑和格式, feature 表示被運(yùn)行的feature文件的包路徑阁将, glue中配置steps的包路徑地址膏秫,tags中配置要運(yùn)行的用例的tags名,其實(shí)~符號(hào)表示除了這個(gè)tags的所有tags.
通過(guò)Jenkins 執(zhí)行
- 在Pom.xml 文件里面添加運(yùn)行插件做盅,如下:
<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>
- 在Jenkins 中添加Cucumber-JVM reports插件缤削。
- 新建Maven job,配置maven構(gòu)建方式和構(gòu)建后的測(cè)試報(bào)告展示吹榴。
Cucumber-JVM reports 提供了非常漂亮的report亭敢,如下:
最后附上項(xiàng)目地址:https://github.com/MeYoung/cucumber_restassured