赞
踩
rest教程
REST Assured is a Java Domain Specific Language API for simplifying testing of RESTful web services. REST Assured API can be used to invoke REST web services and match response content to test them.
REST Assured是Java域特定语言API,用于简化RESTful Web服务的测试。 REST安全的API可用于调用REST Web服务并匹配响应内容以对其进行测试。
REST Assured can be used to test XML as well as JSON based web services. REST Assured can be integrated with JUnit and TestNG frameworks for writing test cases for our application.
REST Assured可用于测试XML以及基于JSON的Web服务。 REST Assured可以与JUnit和TestNG框架集成,以便为我们的应用程序编写测试用例。
REST Assured supports POST, GET, PUT, DELETE, OPTIONS, PATCH, and HEAD requests and can be used to validate and verify the response of these requests.
REST Assured支持POST,GET,PUT,DELETE,OPTIONS,PATCH和HEAD请求,可用于验证和验证这些请求的响应。
REST Assured is implemented in Groovy and uses the builder pattern to create requests, set headers, parse the response and then match them with expected data. It uses Hamcrest Matchers for comparing actual response with the expected response.
REST Assured在Groovy中实现,并使用构建器模式创建请求,设置标头,解析响应,然后将其与预期数据匹配。 它使用Hamcrest Matchers将实际响应与预期响应进行比较。
One of the powerful features of REST assured is the support of XML Path and JSON Path syntax to check specific elements of the response data. It’s very similar to using XPath API.
REST确保的强大功能之一是对XML Path和JSON Path语法的支持,以检查响应数据的特定元素。 这与使用XPath API非常相似。
Before we create our REST Assured tests, we need some web services to test. Below are the additional components used in this tutorial.
在创建REST保证测试之前,我们需要一些Web服务进行测试。 以下是本教程中使用的其他组件。
- {
- "employees": [
- {
- "id": 1,
- "name": "Pankaj",
- "salary": "10000"
- },
- {
- "name": "David",
- "salary": "5000",
- "id": 2
- }
- ]
- }
Below image shows the APIs exposed by json-server mock web service.
JSON Server :这是一个创建基于JSON的模拟Web服务的好工具,它所需要的只是一个示例JSON文件。 它会自动为我们创建GET,POST,PUT,DELETE API端点。 我已经在JSON Server教程中对此进行了介绍。 JSON下面是基于示例JSON的Web服务的输入。- {
- "employees": [
- {
- "id": 1,
- "name": "Pankaj",
- "salary": "10000"
- },
- {
- "name": "David",
- "salary": "5000",
- "id": 2
- }
- ]
- }
下图显示了json-server模拟Web服务公开的API。
Create a maven based project in Eclipse and add Rest Assured and TestNG dependencies.
在Eclipse中创建一个基于Maven的项目,并添加Rest Assured和TestNG依赖项。
- <dependency>
- <groupId>io.rest-assured</groupId>
- <artifactId>rest-assured</artifactId>
- <version>3.1.0</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>6.14.3</version>
- <scope>test</scope>
- </dependency>
Below code snippet shows how to call GET method and test response JSON elements. Notice the use of static imports, some of them will be used in subsequent examples.
下面的代码片段显示了如何调用GET方法和测试响应JSON元素。 注意使用静态导入 ,其中一些将在后续示例中使用。
- import static io.restassured.RestAssured.delete;
- import static io.restassured.RestAssured.get;
- import static io.restassured.RestAssured.given;
- import static org.hamcrest.Matchers.hasItems;
-
- import org.hamcrest.Matchers;
- import org.testng.annotations.DataProvider;
- import org.testng.annotations.Test;
-
- import io.restassured.http.ContentType;
- import io.restassured.response.Response;
-
- public class RESTAssuredJSONTests {
-
- final static String ROOT_URI = "https://localhost:7000/employees";
-
- @Test
- public void simple_get_test() {
- Response response = get(ROOT_URI + "/list");
- System.out.println(response.asString());
-
- response.then().body("id", hasItems(1, 2));
- response.then().body("name", hasItems("Pankaj"));
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Here is another complex example, where we are using TestNG DataProvider with REST Assured.
这是另一个复杂的示例,其中我们将TestNG DataProvider与REST Assured一起使用。
- @Test(dataProvider = "dpGetWithParam")
- public void get_with_param(int id, String name) {
- get(ROOT_URI + "/get/" + id).then().body("name", Matchers.is(name));
- }
-
- @DataProvider
- public Object[][] dpGetWithParam() {
- Object[][] testDatas = new Object[][] {
- new Object[] { 1, "Pankaj" },
- new Object[] { 2, "David" } };
- return testDatas;
- }
Below code snippet shows how to create JSON Request with different headers, then test the response elements.
下面的代码片段显示了如何使用不同的标头创建JSON请求,然后测试响应元素。
- @Test
- public void post_test() {
- Response response = given().
- contentType(ContentType.JSON)
- .accept(ContentType.JSON)
- .body("{\"name\": \"Lisa\",\"salary\": \"2000\"}")
- .when()
- .post(ROOT_URI + "/create");
- System.out.println("POST Response\n" + response.asString());
- // tests
- response.then().body("id", Matchers.any(Integer.class));
- response.then().body("name", Matchers.is("Lisa"));
- }
- @Test
- public void put_test() {
- Response response = given()
- .contentType(ContentType.JSON)
- .accept(ContentType.JSON)
- .body("{\"name\": \"Lisa Tamaki\",\"salary\": \"20000\"}")
- .when()
- .put(ROOT_URI + "/update/3");
- System.out.println("PUT Response\n" + response.asString());
- // tests
- response.then().body("id", Matchers.is(3));
- response.then().body("name", Matchers.is("Lisa Tamaki"));
- response.then().body("salary", Matchers.is("20000"));
- }
- @Test
- public void delete_test() {
- Response response = delete(ROOT_URI + "/delete/3");
- System.out.println(response.asString());
- System.out.println(response.getStatusCode());
- // check if id=3 is deleted
- response = get(ROOT_URI + "/list");
- System.out.println(response.asString());
- response.then().body("id", Matchers.not(3));
- }
Below images show the output from our Jersey REST web service.
下图显示了我们的Jersey REST Web服务的输出。
Success Case – Response Code 200
成功案例–响应码200
Error Case – Response Code 500
错误案例-响应码500
Here is our test class showing how to test both the cases using REST Assured.
这是我们的测试类,显示了如何使用REST Assured测试这两种情况。
- package com.journaldev.restassured;
-
- import static io.restassured.RestAssured.given;
-
- import org.hamcrest.Matchers;
- import org.testng.Assert;
- import org.testng.annotations.Test;
-
- import io.restassured.http.ContentType;
- import io.restassured.response.Response;
-
- public class RESTAssuredXMLTests {
-
-
- @Test
- public void post_xml_test() {
- Response response = given().
- contentType(ContentType.XML)
- .accept(ContentType.XML)
- .body("<empRequest>\n" +
- " <id>1</id>\n" +
- " <name>PK</name>\n" +
- "</empRequest>")
- .when()
- .post("https://localhost:8080/My-Jersey-Project/rest/emp/getEmp");
- System.out.println("POST Response\n" + response.asString());
- // tests
- Assert.assertEquals(response.getStatusCode(),200);
- response.then().body("empResponse.id", Matchers.is("1"));
- response.then().body("empResponse.name", Matchers.is("PK"));
- }
-
- @Test
- public void post_xml_error_test() {
- Response response = given().
- contentType(ContentType.XML)
- .accept(ContentType.XML)
- .body("<empRequest>\n" +
- " <id>2</id>\n" +
- " <name>PK</name>\n" +
- "</empRequest>")
- .when()
- .post("https://localhost:8080/My-Jersey-Project/rest/emp/getEmp");
- System.out.println("POST Error Response\n" + response.asString());
- // tests
- response.then().body("errorResponse.errorId", Matchers.is("2"));
- response.then().body("errorResponse.errorCode", Matchers.is("Wrong ID"));
- Assert.assertEquals(response.getStatusCode(),500);
- }
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
We get the following output when above test class is executed.
当执行上述测试类时,我们得到以下输出。
- POST Error Response
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?><errorResponse><errorCode>Wrong ID</errorCode><errorId>2</errorId></errorResponse>
- POST Response
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?><empResponse><id>1</id><name>PK</name></empResponse>
- PASSED: post_xml_error_test
- PASSED: post_xml_test
Notice that the major change is where we are setting the request body, there is no change in the way we are retrieving response elements, whether it’s JSON or XML response. This makes REST Assured powerful and easy to learn and use.
注意,主要的变化是我们设置请求主体的位置,检索响应元素的方式没有任何变化,无论是JSON还是XML响应。 这使得REST安全确保功能强大且易于学习和使用。
REST Assured helps us in testing our REST APIs easily. It integrates seamlessly with TestNG and JUnit. JSON Path and XML Path allows us to easily parse the response data and test specific elements. Since it uses Hamcrest API, there are many options to match actual result with expected data.
REST Assured帮助我们轻松测试REST API。 它与TestNG和JUnit无缝集成。 JSON Path和XML Path使我们能够轻松解析响应数据并测试特定元素。 由于它使用Hamcrest API,因此有许多选项可将实际结果与预期数据进行匹配。
Reference: Official Documentation
参考: 官方文档
rest教程
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。