待解决的问题:
- 访问https的RESTFUL web service
- JSON schema validation
- ValidatableResponse与Response的使用
- TestNG的DataProvider结合使用
package restAssuredAPITest.restAssuredAPITest;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.config.SSLConfig;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.response.ValidatableResponse;
import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static com.jayway.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.junit.After;
import org.junit.Before;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class RestAPISample {
@BeforeClass
public void before() {
//"http://petstore.swagger.io/v2/pet/2";
//"https://api.douban.com/v2/book/1220562";
RestAssured.baseURI = "http://petstore.swagger.io";
// RestAssured.useRelaxedHTTPSValidation();
// RestAssured.port = 8080;
}
@Test
//URL为http://api.douban.com/v2/book/1220562
//判断Json中的返回信息title
public void testGetBook() {
// Response response = given().get("");
// response.print();
// given()
// .config(RestAssured.config().sslConfig(
// new SSLConfig().allowAllHostnames())).
given().config((RestAssured.config().sslConfig(new SSLConfig().relaxedHTTPSValidation()))).
// given().relaxedHTTPSValidation("TLS").when().
get("/1220562").then().body("title", equalTo("满月之夜白鲸现"));
}
@Test
//URL为http://api.douban.com/v2/book/search?q=java8
//判断Json中的返回信息关键字为“java8”的书本的数目
public void testSearchBook() {
given().param("q", "java8").when().get("/search").then().body("count", equalTo(2));
}
@Test
//解析JSON
public void testParseJson() {
ValidatableResponse resp = get("/1220562").then();
//判断返回Json数据的title
resp.body("title", equalTo("满月之夜白鲸现"));
//判断二级属性rating.max的值
resp.body("rating.max", equalTo(10));
//调用数组的方法判断数组的大小
resp.body("tags.size()", is(8));
//判断数组第一个对象的值
resp.body("tags[0].name", equalTo("片山恭一"));
//判断数组中是否有该元素
resp.body("author", hasItems("[日] 片山恭一"));
}
@Test
public void testJsonScheme() {
for(int i=0;i<4;i++) {
String resp = get("/v2/pet/2").getBody().asString();
System.out.println(resp);
String ID = get("/v2/pet/2").getBody().jsonPath().get("category.id").toString();
System.out.print(ID);
}
//"http://petstore.swagger.io";//
// ValidatableResponse resp = get("/v2/pet/2").then();
resp.body("title", equalTo("满月之夜白鲸现"));
// resp.assertThat().body(matchesJsonSchemaInClasspath("schema.json"));
String resp = get("/v2/pet/2").getBody().asString();
System.out.println(resp);
// expect().statusCode(200).given().auth().preemptive().basic("", "")
// .headers("Accept", "application/JSON").when().get("/v2/pet/2")
// .then().assertThat().body(matchesJsonSchemaInClasspath("schema.json"));
String ID = get("/v2/pet/2").getBody().jsonPath().get("category.id").toString();
System.out.print(ID);
}
@AfterClass
public void after() {
}
}