REST Assured.Day 1
Кратко о REST API
Введение в REST Assured:
Ознакомиться с REST Assured
Пример кода для установки REST Assured
Написание первого теста
Кратко о REST API
Введение в REST Assured:
Ознакомиться с REST Assured
Пример кода для установки REST Assured
Написание первого теста
REST (Representational State Transfer) API – это архитектурный стиль для разработки сетевых приложений, основанный на принципах HTTP. Он позволяет взаимодействовать с удалёнными серверами, обмениваясь данными в формате JSON или XML.
Основные принципы REST API:
Ресурсы: Объекты или данные, к которым можно получить доступ или модифицировать. Каждый ресурс идентифицируется уникальным URL.
HTTP методы: REST использует основные HTTP методы для операций с ресурсами:
Представление ресурсов: Ресурсы передаются между клиентом и сервером в формате JSON или XML.
Без состояния (Stateless): Каждый запрос к серверу должен содержать всю необходимую информацию для выполнения этого запроса. Сервер не должен хранить состояние клиента между запросами.
Однозначность (Uniform Interface): Интерфейс должен быть единообразным для всех ресурсов.
Слой взаимодействия (Layered System): Клиент не должен знать о каких-либо промежуточных слоях между ним и сервером.
REST API является популярным выбором для создания веб-сервисов из-за своей простоты, масштабируемости и гибкости. Он широко применяется в разработке мобильных приложений, веб-приложений.

REST Assured – это библиотека для тестирования RESTful веб-сервисов на Java. Она предоставляет возможности для создания, отправки и проверки HTTP запросов и ответов.
Основные преимущества REST Assured:
–Легко использовать: не требует знания специфических языков программирования или фреймворков.
-Возможность тестировать любые методы HTTP: GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH.
-Поддержка проверки подлинности: Basic, OAuth, Digest, NTLM, Form.
-Поддержка сериализации/десериализации JSON и XML.
–Возможность проверять ответы с помощью специфических условий.
-Возможность тестирования запросов с параметрами, заголовками, телом запроса и телом ответа.
Основные функции REST Assured:
-Создание и отправка запросов HTTP.
-Проверка ответов HTTP.
–Парсинг и проверка JSON или XML ответов.
-Поддержка аутентификации.
–Поддержка сериализации/десериализации JSON и XML.
-Поддержка файлов для мультипартов.
–Поддержка Cookies.
–Поддержка сессий.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
Чтобы настроить IntelliJ IDEA для тестирования RESTful API с использованием REST Assured, вам понадобится выполнить несколько шагов. Вот пошаговая инструкция:
Если вы еще не установили IntelliJ IDEA Community Edition, вы можете сделать это по следующей ссылке: https://www.jetbrains.com/idea/download/
Если у вас еще не установлен JDK, вы можете скачать его с официального сайта Oracle: https://www.oracle.com/java/technologies/javase-jdk11-downloads.html
Если у вас еще не установлен Maven, вы можете скачать его с официального сайта Apache Maven: https://maven.apache.org/download.cgi
“Откройте IntelliJ IDEA (версия 2024.1) и выберите File -> New -> Project.
Выберите проект Java.
Укажите название проекта в поле “Name”.
Для Build System выберите Maven в качестве типа проекта.
Выберите версию установленной JDK.
Нажмите “Create”

Откройте файл pom.xml в корневой директории проекта и добавьте следующую зависимость в раздел <dependencies>:
<!– https://mvnrepository.com/artifact/io.rest-assured/rest-assured –>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
Добавить еще зависимость jUnit.
JUnit – фреймворк для написания автоматизированных тестов на языке Java. JUnit позволяет создавать и запускать тестовые случаи для проверки своего кода. В контексте этого проекта JUnit используется для написания и запуска тестовых случаев для REST API с использованием REST Assured.
<!– https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine –>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>


Вот пример теста, который использует REST Assured для выполнения GET-запроса к API:
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class BookingAPITest {
@BeforeAll
public static void setup() {
RestAssured.baseURI = “https://restful-booker.herokuapp.com”;
}
@Test
public void testGetBookingById() {
given()
.pathParam(“id”, 1)
.when()
.get(“/booking/{id}”)
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body(“firstname”, equalTo(“Susan”))
.body(“lastname”, equalTo(“Brown”))
.body(“totalprice”, equalTo(374))
.body(“depositpaid”, equalTo(true))
.body(“bookingdates.checkin”, equalTo(“2024-05-01”))
.body(“bookingdates.checkout”, equalTo(“2024-05-10”))
.body(“additionalneeds”, equalTo(“Breakfast”));
}

Этот код – это простой пример тестирования API с использованием библиотеки REST Assured в среде JUnit 5. Давайте разберем его построчно:
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
Импорт необходимых классов из библиотеки REST Assured и JUnit 5.
public class BookingAPITest {
@BeforeAll
public static void setup() {
RestAssured.baseURI = “https://restful-booker.herokuapp.com”;
}
Объявление класса теста и метода инициализации (@BeforeAll), который будет выполняться перед выполнением всех тестов. Метод setup() устанавливает базовый URI для всех запросов. В данном случае, используется API сервиса для бронирования на сайте https://restful-booker.herokuapp.com.
@Test
public void testGetBookingById() {
given()
.pathParam(“id”, 1)
.when()
.get(“/booking/{id}”)
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body(“firstname”, equalTo(“Susan”))
.body(“lastname”, equalTo(“Brown”))
.body(“totalprice”, equalTo(374))
.body(“depositpaid”, equalTo(true))
.body(“bookingdates.checkin”, equalTo(“2024-05-01”))
.body(“bookingdates.checkout”, equalTo(“2024-05-10”))
.body(“additionalneeds”, equalTo(“Breakfast”));
}
Метод тестирования testGetBookingById(). В данном случае, он выполняет GET-запрос для получения информации о бронировании по ID.
given(): Указывает начальное состояние запроса..pathParam("id", 1): Устанавливает параметр пути (path parameter) с именем “id” и значением 1.when(): Выполняет запрос..get("/booking/{id}"): Выполняет GET-запрос по адресу “/booking/{id}”.then(): Проверяет ответ на запрос..statusCode(200): Проверяет, что статус-код ответа равен 200 (OK)..contentType(ContentType.JSON): Проверяет, что тип содержимого ответа JSON..body("firstname", equalTo("Susan")): Проверяет, что значение поля “firstname” в ответе равно “Susan”..body("lastname", equalTo("Brown")): Проверяет, что значение поля “lastname” в ответе равно “Brown”..body("totalprice", equalTo(374)): Проверяет, что значение поля “totalprice” в ответе равно 374..body("depositpaid", equalTo(true)): Проверяет, что значение поля “depositpaid” в ответе равно true..body("bookingdates.checkin", equalTo("2024-05-01")): Проверяет, что значение поля “checkin” в объекте “bookingdates” в ответе равно “2024-05-01”..body("bookingdates.checkout", equalTo("2024-05-10")): Проверяет, что значение поля “checkout” в объекте “bookingdates” в ответе равно “2024-05-10”..body("additionalneeds", equalTo("Breakfast")): Проверяет, что значение поля “additionalneeds” в ответе равно “Breakfast”.Перед началом написания тестов необходимо тщательно изучить документацию по REST API. Без этого этапа невозможно составить тест-кейсы, которые охватывают бы все сценарии использования. В документации вы найдете все необходимые эндпоинты, методы запросов, параметры и ожидаемые ответы. Это позволит вам глубоко понять, как взаимодействовать с API, и убедиться, что ваши тесты будут полноценно покрывать функциональность, исключая ошибки в работе.
Шаги:
Отправить POST-запрос на /auth с корректными учетными данными:
“username”: “admin”
“password”: “password123”
Ожидаемый результат:
Шаги:
Отправить POST-запрос на /auth с неправильным именем пользователя:
“username”: “admin1”
“password”: “password123”
Ожидаемый результат:
Шаги:
Отправить POST-запрос на /auth с неправильным паролем:
“username”: “admin”
“password”: “password1234”
Ожидаемый результат:
Шаги:
Отправить POST-запрос на /auth с произвольными учетными данными.
Ожидаемый результат:
package activities; // Declaration of the package where this class is located
import io.restassured.RestAssured; // Importing the RestAssured class from the rest-assured library
import io.restassured.http.ContentType; // Importing the ContentType class from the rest-assured library
import io.restassured.response.ValidatableResponse; // Importing the ValidatableResponse class from the rest-assured library
import org.junit.jupiter.api.Assertions; // Importing the Assertions class from the JUnit Jupiter library
import org.junit.jupiter.api.DisplayName; // Importing the DisplayName annotation from the JUnit Jupiter library
import org.junit.jupiter.api.Test; // Importing the Test annotation from the JUnit Jupiter library
import static org.hamcrest.Matchers.lessThan; // Static import of the lessThan() method from the Matchers class in the Hamcrest library
public class AuthActivities { // Declaration of the AuthActivities class
private String baseUrl = “https://restful-booker.herokuapp.com”; // Defining the base URL for the API
private String basePath = “/auth”; // Defining the base path for the API
// Test to get a token with valid credentials
@Test // Annotation indicating that this method is a test
@DisplayName(“Get token with valid credentials”) // Annotation specifying the display name for this test
public void test1() { // Method declaration for test1()
// Arrange
String body = “””
{
“username” : “admin”,
“password” : “password123”
}
“””; // Defining a JSON string to be sent in the request. It contains the username and password.
// Act
ValidatableResponse response = RestAssured // Invoking RestAssured to send an HTTP request
.given() // Starting a chain of calls to set up the request
.basePath(basePath) // Setting the base path for the request
.baseUri(baseUrl) // Setting the base URL for the request
.contentType(ContentType.JSON) // Setting the request content type as JSON
.body(body) // Passing the request body
.log().all() // Logging all actions
.when() // Completing the request setup and starting its execution
.post() // Sending a POST request
.then() // Starting response validation
.log().all(); // Logging all actions
// Assert
Assertions.assertNotNull(response.extract().asString()); // Checking that the response is not null
Assertions.assertTrue(response.extract().asString().contains(“token”)); // Checking for the presence of “token” in the response
}
// Test to get a token with an invalid username
@Test // Annotation indicating that this method is a test
@DisplayName(“Get token with invalid username”) // Annotation specifying the display name for this test
public void test2() { // Method declaration for test2()
// Arrange
String body = “””
{
“username” : “admin1”,
“password” : “password123”
}
“””; // Defining a JSON string to be sent in the request. It contains an incorrect username
// Act
ValidatableResponse response = RestAssured // Invoking RestAssured to send an HTTP request
.given() // Starting a chain of calls to set up the request
.basePath(basePath) // Setting the base path for the request
.baseUri(baseUrl) // Setting the base URL for the request
.contentType(ContentType.JSON) // Setting the request content type as JSON
.body(body) // Passing the request body
.when() // Completing the request setup and starting its execution
.post() // Sending a POST request
.then(); // Starting response validation
// Assert
Assertions.assertNotNull(response.extract().asString()); // Checking that the response is not null
Assertions.assertTrue(response.extract().asString().contains(“reason”)); // Checking for the presence of “reason” in the response
}
// Test to get a token with an invalid password
@Test // Annotation indicating that this method is a test
@DisplayName(“Get token with invalid password”) // Annotation specifying the display name for this test
public void test3() { // Method declaration for test3()
// Arrange
String body = “””
{
“username” : “admin”,
“password” : “password1234”
}
“””; // Defining a JSON string to be sent in the request. It contains an incorrect password
// Act
ValidatableResponse response = RestAssured // Invoking RestAssured to send an HTTP request
.given() // Starting a chain of calls to set up the request
.basePath(basePath) // Setting the base path for the request
.baseUri(baseUrl) // Setting the base URL for the request
.contentType(ContentType.JSON) // Setting the request content type as JSON
.body(body) // Passing the request body
.when() // Completing the request setup and starting its execution
.post() // Sending a POST request
.then(); // Starting response validation
// Assert
Assertions.assertNotNull(response.extract().asString()); // Checking that the response is not null
Assertions.assertTrue(response.extract().asString().contains(“reason”)); // Checking for the presence of “reason” in the response
}
// Test to check the response time is less than 3000ms
@Test // Annotation indicating that this method is a test
@DisplayName(“Response time less than 3000ms”) // Annotation specifying the display name for this test
public void test5() { // Method declaration for test5()
// Arrange
String body = “””
{
“username” : “admin”,
“password” : “password1234”
}
“””; // Defining a JSON string to be sent in the request. It contains an incorrect password
// Act
ValidatableResponse response = RestAssured // Invoking RestAssured to send an HTTP request
.given() // Starting a chain of calls to set up the request
.basePath(basePath) // Setting the base path for the request
.baseUri(baseUrl) // Setting the base URL for the request
.contentType(ContentType.JSON) // Setting the request content type as JSON
.body(body) // Passing the request body
.when() // Completing the request setup and starting its execution
.post() // Sending a POST request
.then(); // Starting response validation
// Assert
response.assertThat().time(lessThan(3000L)); // Checking that the response time is less than 3000ms
}
}
Шаги:
Отправить GET-запрос на эндпоинт /booking.
Ожидаемый результат:
Шаги:
Отправить GET-запрос на эндпоинт /booking.
Ожидаемый результат:
Шаги:
Отправить GET-запрос на эндпоинт /booking.
Ожидаемый результат:
Шаги:
Отправить GET-запрос на эндпоинт /booking.
Ожидаемый результат:
package activities; // Declaration of the package where this class is located
import io.restassured.RestAssured; // Importing the RestAssured class from the rest-assured library
import io.restassured.http.ContentType; // Importing the ContentType class from the rest-assured library
import io.restassured.response.ValidatableResponse; // Importing the ValidatableResponse class from the rest-assured library
import org.junit.jupiter.api.Assertions; // Importing the Assertions class from the JUnit Jupiter library
import org.junit.jupiter.api.DisplayName; // Importing the DisplayName annotation from the JUnit Jupiter library
import org.junit.jupiter.api.Test; // Importing the Test annotation from the JUnit Jupiter library
import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; // Importing the matchesJsonSchemaInClasspath() method from the JsonSchemaValidator class in the rest-assured library
import static org.hamcrest.Matchers.lessThan; // Static import of the lessThan() method from the Matchers class in the Hamcrest library
public class GetActivities { // Declaration of the GetActivities class
private String baseUrl = “https://restful-booker.herokuapp.com”; // Defining the base URL for the API
private String basePath = “/booking”; // Defining the base path for the API
// Test to get all bookings
@Test // Annotation indicating that this method is a test
@DisplayName(“Get All Bookings”) // Annotation specifying the display name for this test
public void test1() { // Method declaration for test1()
// Arrange
// Act
ValidatableResponse response = RestAssured // Invoking RestAssured to send an HTTP request
.given() // Starting a chain of calls to set up the request
.basePath(basePath) // Setting the base path for the request
.baseUri(baseUrl) // Setting the base URL for the request
.contentType(ContentType.JSON) // Setting the request content type as JSON
.when() // Completing the request setup and starting its execution
.get() // Sending a GET request
.then() // Starting response validation
.log().all(); // Logging all actions
// Assert
Assertions.assertNotNull(response.extract().asString()); // Checking that the response is not null
Assertions.assertTrue(response.extract().asString().contains(“bookingid”)); // Checking for the presence of “bookingid” in the response
}
// Test to check if the status code is 200
@Test // Annotation indicating that this method is a test
@DisplayName(“Status code is 200”) // Annotation specifying the display name for this test
public void test2() { // Method declaration for test2()
// Arrange
// Act
ValidatableResponse response = RestAssured // Invoking RestAssured to send an HTTP request
.given() // Starting a chain of calls to set up the request
.basePath(basePath) // Setting the base path for the request
.baseUri(baseUrl) // Setting the base URL for the request
.contentType(ContentType.JSON) // Setting the request content type as JSON
.when() // Completing the request setup and starting its execution
.get() // Sending a GET request
.then(); // Starting response validation
// Assert
response.assertThat().statusCode(200); // Checking that the status code is 200
}
// Test to check if the response time is less than 3000ms
@Test // Annotation indicating that this method is a test
@DisplayName(“Response time less than 3000ms”) // Annotation specifying the display name for this test
public void test3() { // Method declaration for test3()
// Arrange
// Act
ValidatableResponse response = RestAssured // Invoking RestAssured to send an HTTP request
.given() // Starting a chain of calls to set up the request
.basePath(basePath) // Setting the base path for the request
.baseUri(baseUrl) // Setting the base URL for the request
.contentType(ContentType.JSON) // Setting the request content type as JSON
.when() // Completing the request setup and starting its execution
.get() // Sending a GET request
.then(); // Starting response validation
// Assert
response.assertThat().time(lessThan(3000L)); // Checking that the response time is less than 3000ms
}
// Test to check if the response matches the defined schema
@Test // Annotation indicating that this method is a test
@DisplayName(“Response matches schema”) // Annotation specifying the display name for this test
public void test4() { // Method declaration for test4()
// Arrange
// Act
ValidatableResponse response = RestAssured // Invoking RestAssured to send an HTTP request
.given() // Starting a chain of calls to set up the request
.basePath(basePath) // Setting the base path for the request
.baseUri(baseUrl) // Setting the base URL for the request
.contentType(ContentType.JSON) // Setting the request content type as JSON
.when() // Completing the request setup and starting its execution
.get() // Sending a GET request
.then(); // Starting response validation
// Assert
response.assertThat().body(matchesJsonSchemaInClasspath(“bookingGetAllResponseSchema.json”)); // Checking that the response matches the defined schema
}
}

Но лучше напишите все вручную
Если у вас возникли проблемы с запуском тестов или у вас есть другие вопросы, не стесняйтесь обращаться к нам.

После завершения написания тестов, пожалуйста, архивируйте ваш проект в формате ZIP или RAR и отправьте нам для проверки.
Мы также присутствуем в социальных сетях! Подписывайтесь на нас и получайте последние новости, акции, скидки, бесплатные тренинги и участие в марафонах.
Будем рады видеть вас в нашем сообществе!
Публичная оферта. Авторское право © 2024 Школа подготовки тестировщиков