📜 ⬆️ ⬇️

Simple examples of sending GET and POST requests for Java using the Rest-Assured library

Nowadays, automatists are increasingly asking to automate not only functional tests for the web using Selenium, but also to write tests on the API. In particular, for web services of the REST architecture.

In this note, I will give a couple of simple examples of using Rest-Assured library, intended for testing REST services. It supports all types of requests: POST, GET, PUT, DELETE, OPTIONS, PATCH, HEAD and can be used to check the answers for sent requests.

As a build system, I use Maven, as the most simple and convenient. So, add the following dependencies to pom.xml:

<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.0.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180130</version> </dependency> 

Further I provide actual code examples. I think comments are unnecessary.

Example of sending a GET request

 package com.example.tests; import static io.restassured.RestAssured.get; import io.restassured.response.Response; import org.json.JSONArray; import org.json.JSONException; import org.testng.Assert; import org.testng.annotations.Test; public class RestAssuredTestArticle { @Test(description = "GET") public void getRequestExampleTest() throws JSONException { Response response = get("http://restcountries.eu/rest/v1/name/russia"); JSONArray jsonResponse = new JSONArray(response.asString()); String capital = jsonResponse.getJSONObject(0).getString("capital"); Assert.assertEquals(capital, "Moscow"); } } 

An example of sending a POST request

 package com.example.tests; import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Date; public class RestAssuredTestArticle { @Test(description = "POST") public void postRequestExampleTest() { String someRandomString = String.format("%1$TH%1$TM%1$TS", new Date()); JSONObject requestBody = new JSONObject(); requestBody.put("FirstName", someRandomString); requestBody.put("LastName", someRandomString); requestBody.put("UserName", someRandomString); requestBody.put("Password", someRandomString); requestBody.put("Email", someRandomString + "@gmail.com"); RequestSpecification request = RestAssured.given(); request.header("Content-Type", "application/json"); request.body(requestBody.toString()); Response response = request.post("http://restapi.demoqa.com/customer/register"); int statusCode = response.getStatusCode(); Assert.assertEquals(statusCode, 201); String successCode = response.jsonPath().get("SuccessCode"); Assert.assertEquals(successCode, "OPERATION_SUCCESS"); System.out.println(response.getBody().asString()); } } 

Source: https://habr.com/ru/post/438706/