rest教程_REST保证教程

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)

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非常相似。

REST保证教程先决条件 (REST Assured Tutorial Prerequisites)

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服务进行测试。 以下是本教程中使用的其他组件。

  1. JSON Server: It’s a great tool to create mock JSON based web services, all it requires is a sample JSON file. It automatically creates GET, POST, PUT, DELETE API endpoints for us. I have written about it at JSON Server tutorial. Below JSON is the input for our example JSON based web service.
    {
      "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。

  2. Jersey: I am using XML based web service created in Jersey Tutorial. You can download this project from our GitHub Repository and run on tomcat.

    泽西岛 :我正在使用在泽西岛教程中创建的基于XML的Web服务。 您可以从我们的GitHub存储库下载该项目并在tomcat 运行。
  3. TestNG: I will use TestNG to create test cases with REST Assured, you can use JUnit too. You can learn about TestNG framework through our TestNG Tutorials.

    TestNG :我将使用TestNG通过REST Assured创建测试用例,您也可以使用JUnit。 您可以通过我们的TestNG教程了解TestNG框架。

REST保证教程 (REST Assured Tutorial)

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>

REST保证GET测试 (REST Assured GET Test)

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"));
}
}

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;
}

REST保证POST示例 (REST Assured POST Example)

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"));
}

REST保证的PUT示例 (REST Assured PUT Example)

@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"));
}

REST保证的DELETE示例 (REST Assured DELETE Example)

@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));
}

REST保证的XML REST Web服务示例 (REST Assured XML REST Web Services Example)

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

REST Assured XML Error Response Example

错误案例-响应码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);
	}

}

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安全确保功能强大且易于学习和使用。

摘要 (Summary)

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,因此有许多选项可将实际结果与预期数据进行匹配。

GitHub Repository. GitHub Repository下载完整的示例项目。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/21501/rest-assured-tutorial

rest教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值