REST Assured – это библиотека для тестирования REST API на языке Java. Она предоставляет удобные средства для создания и выполнения HTTP-запросов к вашему API, а также проверки ответов на соответствие ожидаемым результатам.
REST - это стиль архитектуры программного обеспечения, основанный на принципах, описанных в докладе Роя Филдинга в 2000 году. Он предоставляет легковесный и гибкий способ создания веб-сервисов.
В REST, данные представлены как ресурсы, которые могут быть представлены в виде URL-адресов. Ресурсы - это ключевые сущности вашего приложения, например, пользователи, продукты или заказы.
Получение данных с ресурса. POST: Создание нового ресурса. PUT: Обновление существующего ресурса. DELETE: Удаление ресурса.
HTTP-статусы указывают на результат выполнения запроса. Например, 200 OK обозначает успешное выполнение, 404 Not Found - отсутствие запрашиваемого ресурса и т.д.
Давайте начнем
Creates a new auth token to use for access to the PUT and DELETE /booking
POST https://booking-api-dev.herokuapp.com/auth
Header
Content-Type String
Default value: application/json
Request body
username String Default value: admin
password String Defaut value: password123
Success 200
token String
{
“username”: “admin”,
“password”: “password123”
}
Returns the ids of all the bookings that exist within the API. Can take optional query strings to search and return a subset of booking ids.
GET https://booking-api-dev.herokuapp.com/booking
Filter all ids
https://booking-api-dev.herokuapp.com/booking
Filter by name
https://booking-api-dev.herokuapp.com/booking?firstname=sally&lastname=brown
Filter by checkin/checkout date
https://booking-api-dev.herokuapp.com/booking?checkin=2014-03-13&checkout=2014-05-21
Parameter
firstname optional String
lastname optional String
checkin optional date(Format must be CCYY-MM-DD)
checkin optional date (Format must be CCYY-MM-DD)
Success 200
object object[] Array of objects that contain unique booking IDs
object.bookingid number ID of a specific booking that matches search criteria
Returns a specific booking based upon the booking id provided
GET https://booking-api-dev.herokuapp.com/booking/:id
Header
Accept string Defaul value: application/json
Url parameter
id String
Success 200
firstname String
Firstname for the guest who made the booking
lastname String
Lastname for the guest who made the booking
totalprice Number
The total price for the booking
depositpaid Boolean
Whether the deposit has been paid or not
bookingdates Object
Sub-object that contains the checkin and checkout dates
checkin Date
Date the guest is checking in
checkout Date
Date the guest is checking out
additionalneeds String
Any other needs the guest has
{
“firstname”: “Sally”,
“lastname”: “Brown”,
“totalprice”: 111,
“depositpaid”: true,
“bookingdates”: {
“checkin”: “2023-02-23”,
“checkout”: “2023-10-23”
},
“additionalneeds”: “Breakfast”
}
Creates a new booking in the API
POST https://booking-api-dev.herokuapp.com/booking
Header
Content-Type string Defaut value: application/json
Accept string Default value: application/json
Request body
firstname String
Firstname for the guest who made the booking
lastname String
Lastname for the guest who made the booking
totalprice Number
The total price for the booking
depositpaid Boolean
Whether the deposit has been paid or not
checkin Date
Date the guest is checking in
checkout Date
Date the guest is checking out
Success 200
bookingid Number
ID for newly created booking
booking Object
Object that contains
firstname String
Firstname for the guest who made the booking
lastname String
Lastname for the guest who made the booking
totalprice Number
The total price for the booking
depositpaid Boolean
Whether the deposit has been paid or not
bookingdates Object
Sub-object that contains the checkin and checkout dates
checkin Date
Date the guest is checking in
checkout Date
Date the guest is checking out
additionalneeds String
Any other needs the guest has
additionalneeds String
Any other needs the guest has
{
“bookingid”: 1,
“booking”: {
“firstname”: “Jim”,
“lastname”: “Brown”,
“totalprice”: 111,
“depositpaid”: true,
“bookingdates”: {
“checkin”: “2018-01-01”,
“checkout”: “2019-01-01”
},
“additionalneeds”: “Breakfast”
}
}
Updates a current booking
PUT https://booking-api-dev.herokuapp.com/booking/:id
Header
Content-Type string
Sets the format of payload you are sending. Can be application/json or text/xml
Default value: application/json
Accept string
Sets what format the response body is returned in. Can be application/json or application/xml
Default value: application/json
Cookie string
Sets an authorization token to access the PUT endpoint, can be used as an alternative to the Authorization
Default value: token=<token_value>
Authorization string
YWRtaW46cGFzc3dvcmQxMjM=] Basic authorization header to access the PUT endpoint, can be used as an alternative to the Cookie header
Default value: Basic
URL Parameter
id Number
ID for the booking you want to update
Request body
firstname String
Firstname for the guest who made the booking
lastname String
Lastname for the guest who made the booking
totalprice Number
The total price for the booking
depositpaid Boolean
Whether the deposit has been paid or not
checkin Date
Date the guest is checking in
checkout Date
Date the guest is checking out
additionalneeds String
Any other needs the guest has
Success 200
firstname String
Firstname for the guest who made the booking
lastname String
Lastname for the guest who made the booking
totalprice Number
The total price for the booking
depositpaid Boolean
Whether the deposit has been paid or not
bookingdates Object
Sub-object that contains the checkin and checkout dates
checkin Date
Date the guest is checking in
checkout Date
Date the guest is checking out
additionalneeds String
Any other needs the guest has
{
“firstname” : “James”,
“lastname” : “Brown”,
“totalprice” : 111,
“depositpaid” : true,
“bookingdates” : {
“checkin” : “2018-01-01”,
“checkout” : “2019-01-01”
},
“additionalneeds” : “Breakfast”
}
Updates a current booking with a partial payload
PATCH https://booking-api-dev.herokuapp.com/booking/:id
Header
Content-Type string
Sets the format of payload you are sending. Can be application/json or text/xml
Default value: application/json
Accept string
Sets what format the response body is returned in. Can be application/json or application/xml
Default value: application/json
Cookie string
Sets an authorization token to access the PUT endpoint, can be used as an alternative to the Authorization
Default value: token=<token_value>
Authorization string
YWRtaW46cGFzc3dvcmQxMjM=] Basic authorization header to access the PUT endpoint, can be used as an alternative to the Cookie header
Default value: Basic
URL Parameter
id Number
ID for the booking you want to update
Request body
firstname String
Firstname for the guest who made the booking
lastname String
Lastname for the guest who made the booking
totalprice Number
The total price for the booking
depositpaid Boolean
Whether the deposit has been paid or not
checkin Date
Date the guest is checking in
checkout Date
Date the guest is checking out
additionalneeds String
Any other needs the guest has
Success 200
firstname String
Firstname for the guest who made the booking
lastname String
Lastname for the guest who made the booking
totalprice Number
The total price for the booking
depositpaid Boolean
Whether the deposit has been paid or not
bookingdates Object
Sub-object that contains the checkin and checkout dates
checkin Date
Date the guest is checking in
checkout Date
Date the guest is checking out
additionalneeds String
Any other needs the guest has
{
“firstname” : “James”,
“lastname” : “Brown”,
“totalprice” : 111,
“depositpaid” : true,
“bookingdates” : {
“checkin” : “2018-01-01”,
“checkout” : “2019-01-01”
},
“additionalneeds” : “Breakfast”
}
Returns the ids of all the bookings that exist within the API. Can take optional query strings to search and return a subset of booking ids.
DELETE https://booking-api-dev.herokuapp.com/booking/1
Cookie string
Sets an authorization token to access the DELETE endpoint, can be used as an alternative to the Authorization
Default value: token=<token_value>
Authorization string
YWRtaW46cGFzc3dvcmQxMjM=] Basic authorization header to access the DELETE endpoint, can be used as an alternative to the Cookie header
Default value: Basic
Cookie
curl -X DELETE \
https://booking-api-dev.herokuapp.com/booking/1 \
-H ‘Content-Type: application/json’ \
-H ‘Cookie: token=abc123’
Шаг 1: Установка IntelliJ IDEA
pom.xml: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>
<!– https://mvnrepository.com/artifact/junit/junit –>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
Шаги:
Отправить POST-запрос на создание токена аутентификации к эндпоинту /auth.
{
"username": "admin",
"password": "password123"
}
Проверить, что ответ на запрос имеет статус код 200 (OK).
Проверить, что в ответе есть непустой параметр "token".
Проверить, что параметр "token" соответствует ожидаемому значению "abc123"
Замерить время выполнения запроса и удостовериться, что оно находится в разумных пределах.
Ожидаемый результат:
Токен аутентификации успешно создан, и его значение соответствует ожидаемому. Время выполнения запроса находится в пределах разумных значений.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class CreateAuthToken {
private static final String BASE_URL = "https://booking-api-dev.herokuapp.com";
private static final String USERNAME = "admin";
private static final String PASSWORD = "password123";
@Test
public void authToken() {
RestAssured.baseURI = BASE_URL;
long startTime = System.currentTimeMillis();
String token = given()
.contentType(ContentType.JSON)
.body("{\"username\": \"" + USERNAME + "\", \"password\": \"" + PASSWORD + "\"}")
.when()
.post("/auth")
.then()
.statusCode(200)
.body("token", not(isEmptyOrNullString()))
.body("$", hasKey("token"))
.extract()
.path("token");
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("Token received: " + token);
System.out.println("Request execution time: " + executionTime + " milliseconds");
}
}
Этот код написан на языке Java с использованием библиотеки RestAssured для тестирования REST API.
Давайте разберем код пошагово:
Импорт библиотек:
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
В этом блоке происходит импорт необходимых библиотек для работы с RestAssured и написания тестов.
Определение класса CreateAuthToken:
public class CreateAuthToken {
Этот класс содержит метод для создания аутентификационного токена.
Определение базового URL и учетных данных:
private static final String BASE_URL = “https://booking-api-dev.herokuapp.com”;
private static final String USERNAME = “admin”;
private static final String PASSWORD = “password123”;
Здесь определены константы для базового URL API, имени пользователя и пароля.
Метод authToken():
@Test
public void authToken() {
Этот метод является тестовым методом для создания аутентификационного токена.
Установка базового URI:
RestAssured.baseURI = BASE_URL;
Устанавливается базовый URI для RestAssured.
Отправка POST-запроса для получения токена:
String token = given()
.contentType(ContentType.JSON)
.body(“{\”username\”: \”” + USERNAME + “\”, \”password\”: \”” + PASSWORD + “\”}”)
.when()
.post(“/auth”)
Здесь используется given() для установки параметров запроса, таких как тип контента (JSON) и тело запроса (имя пользователя и пароль).
Метод when() указывает, что сейчас будет выполнен HTTP-запрос POST. .post(“/auth”) указывает на конечную точку API для аутентификации.
Проверка ответа:
.then()
.statusCode(200)
.body(“token”, not(isEmptyOrNullString()))
.body(“$”, hasKey(“token”))
Здесь проверяется, что код ответа равен 200, и в ответе есть не пустой токен. Также проверяется, что ответ содержит ключ “token”.
Извлечение токена:
.extract()
.path(“token”);
Метод extract() используется для извлечения значения токена из ответа.
Вычисление времени выполнения запроса и вывод результатов:
long endTime = System.currentTimeMillis();
long executionTime = endTime – startTime;
System.out.println(“Token received: ” + token);
System.out.println(“Request execution time: ” + executionTime + ” milliseconds”);
Здесь измеряется время выполнения запроса и выводятся результаты, включая полученный токен и время выполнения запроса.
Шаги:
Отправить GET-запрос по адресу https://booking-api-dev.herokuapp.com/booking.
Проверить, что код состояния ответа равен 200 (HTTP/1.1 200 OK).
Проверить, что тип контента в ответе является JSON (Content-Type: application/json).
Проверить, что JSON-ответ не пустой.
Проверить, что в поле "bookingid" присутствуют значения 1, 2, 3, 4.
Проверить, что все значения в поле "bookingid" являются целыми числами.
Проверить, что все значения в поле "bookingid" не являются пустыми (не null).
Ожидаемый результат:
Все проверки пройдены успешно, тест считается успешным.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class GetBookingIds {
@Test
public void getAllBookingIds() {
RestAssured.baseURI = "https://booking-api-dev.herokuapp.com";
given()
.when()
.get("/booking")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body(not(empty()))
.body("bookingid", hasItems(1, 2, 3, 4))
.body("bookingid", everyItem(isA(Integer.class)))
.body("bookingid", everyItem(not(nullValue())));
}
}
Шаги:
Выполнить GET-запрос к "/booking/{id}" с указанным ID бронирования.
Установить заголовок "Accept" со значением "application/json".
Ожидаемый результат:
Проверить, что код состояния ответа равен 200 (OK).
Проверить, что поле "firstname" не пусто.
Проверить, что поле "lastname" не пусто.
Проверить, что значение поля "totalprice" больше 0.
Проверить, что значение поля "depositpaid" является логическим значением.
Проверить, что значение поля "bookingdates.checkin" не пусто.
Проверить, что значение поля "bookingdates.checkout" не пусто.
Проверить, что значение поля "additionalneeds" не пусто.
Проверить, что значение поля "firstname" равно "Sally".
Проверить, что значение поля "lastname" равно "Brown".
Проверить, что значение поля "totalprice" равно 111.
Проверить, что значение поля "depositpaid" равно true.
Проверить, что значение поля "bookingdates.checkin" равно "2013-02-23".
Проверить, что значение поля "bookingdates.checkout" равно "2014-10-23".
import io.restassured.RestAssured;
import org.junit.BeforeClass;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class GetBooking {
@BeforeClass
public static void setup() {
RestAssured.baseURI = "https://booking-api-dev.herokuapp.com";
}
@Test
public void testGetBookingById() {
String bookingId = "1";
String response =
given()
.header("Accept", "application/json")
.when()
.get("/booking/{id}", bookingId)
.then()
.statusCode(200)
.body("firstname", not(emptyOrNullString()))
.body("lastname", not(emptyOrNullString()))
.body("totalprice", greaterThan(0))
.body("depositpaid", isA(Boolean.class))
.body("bookingdates.checkin", not(emptyOrNullString()))
.body("bookingdates.checkout", not(emptyOrNullString()))
.body("firstname", equalTo("Jim"))
.body("lastname", equalTo("Ericsson"))
.body("totalprice", equalTo(543))
.body("depositpaid", equalTo(true))
.body("bookingdates.checkin", equalTo("2020-04-13"))
.body("bookingdates.checkout", equalTo("2022-01-07"))
.extract().asString();
System.out.println("Response: " + response);
}
}
Test Steps:
Open the booking API endpoint in the testing environment.
Prepare a JSON request payload with the following details:
{
"firstname" : "Jim",
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"bookingdates" : {
"checkin" : "2018-01-01",
"checkout" : "2019-01-01"
},
"additionalneeds" : "Breakfast"
}'
Verify that the HTTP response status code is 200 (OK).
Verify that the response body contains the following details:
Booking ID is not null.
First name is "Jim".
Last name is "Brown".
Total price is 111.
Deposit paid is true.
Check-in date is "2018-01-01".
Check-out date is "2019-01-01".
Additional needs are "Breakfast".
Expected Result:
The new booking is successfully created, and the response matches the expected details.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class CreateBooking {
@Test
public void createBookingTest() {
// Set base URI and port
RestAssured.baseURI = "https://booking-api-dev.herokuapp.com";
RestAssured.port = 443; // Assuming the API uses HTTPS
// Request body JSON
String requestBody = "{\n" +
" \"firstname\" : \"Jim\",\n" +
" \"lastname\" : \"Brown\",\n" +
" \"totalprice\" : 111,\n" +
" \"depositpaid\" : true,\n" +
" \"bookingdates\" : {\n" +
" \"checkin\" : \"2018-01-01\",\n" +
" \"checkout\" : \"2019-01-01\"\n" +
" },\n" +
" \"additionalneeds\" : \"Breakfast\"\n" +
"}";
// Send POST request
String response=
given()
.header("Content-Type", ContentType.JSON)
.body(requestBody)
.when()
.post("/booking")
.then()
.statusCode(200)
.body("bookingid", notNullValue())
.body("booking.firstname", equalTo("Jim"))
.body("booking.lastname", equalTo("Brown"))
.body("booking.totalprice", equalTo(111))
.body("booking.depositpaid", equalTo(true))
.body("booking.bookingdates.checkin", equalTo("2018-01-01"))
.body("booking.bookingdates.checkout", equalTo("2019-01-01"))
.body("booking.additionalneeds", equalTo("Breakfast"))
.extract().asString();
System.out.println("Response: " + response);
}
}
Preconditions:
A booking with ID 1 exists in the system.
Test Steps:
Send a PUT request to the endpoint /booking/1 with the following details:
Request Method: PUT
Headers:
Content-Type: application/json
Accept: application/json
Cookie: token=abc123
{
"firstname": "James",
"lastname": "Brown",
"totalprice": 111,
"depositpaid": true,
"bookingdates": {
"checkin": "2018-01-01",
"checkout": "2019-01-01"
},
"additionalneeds": "Breakfast"
}
Expected Status Code: 200
Expected Content Type: application/json
Validate the response body:
"firstname" equals "James"
"lastname" equals "Brown"
"totalprice" equals 111
"depositpaid" equals true
"bookingdates.checkin" equals "2018-01-01"
"bookingdates.checkout" equals "2019-01-01"
"additionalneeds" equals "Breakfast"
Expected Result: The booking information is successfully updated, and the response matches the expected details.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
public class UpdateBooking {
private String authToken;
@Before
public void setup() {
// Define the base URI
RestAssured.baseURI = "https://booking-api-dev.herokuapp.com";
// Step 1: Obtain authentication token
authToken = obtainAuthToken("admin", "password123");
}
@Test
public void updateBooking() {
// Set the booking ID you want to update
int bookingId = 1;
// Define the request body
String requestBody = "{\n" +
" \"firstname\" : \"James\",\n" +
" \"lastname\" : \"Brown\",\n" +
" \"totalprice\" : 111,\n" +
" \"depositpaid\" : true,\n" +
" \"bookingdates\" : {\n" +
" \"checkin\" : \"2018-01-01\",\n" +
" \"checkout\" : \"2019-01-01\"\n" +
" },\n" +
" \"additionalneeds\" : \"Breakfast\"\n" +
"}";
// Perform the PUT request using the obtained token
Response response = RestAssured.given()
.headers("Content-Type", ContentType.JSON.toString(), "Accept", ContentType.JSON.toString(), "Cookie", "token=" + authToken)
.body(requestBody)
.put("/booking/" + bookingId);
// Validate the response
response.then()
.assertThat()
.statusCode(200)
.contentType(ContentType.JSON)
.time(lessThan(5000L)) // Response time less than 5 seconds
.body("firstname", equalTo("James"))
.body("lastname", equalTo("Brown"))
.body("totalprice", equalTo(111))
.body("depositpaid", equalTo(true))
.body("bookingdates.checkin", equalTo("2018-01-01"))
.body("bookingdates.checkout", equalTo("2019-01-01"))
.body("additionalneeds", equalTo("Breakfast"));
}
@After
public void teardown() {
// Reset the base URI after the test
RestAssured.baseURI = null;
}
private String obtainAuthToken(String username, String password) {
// Step 2: Send a POST request to obtain authentication token
String requestBody = "{\n" +
" \"username\" : \"" + username + "\",\n" +
" \"password\" : \"" + password + "\"\n" +
"}";
Response response = RestAssured.given()
.headers("Content-Type", ContentType.JSON.toString(), "Accept", ContentType.JSON.toString())
.body(requestBody)
.post("/auth");
// Step 3: Extract the token from the response
return response.then()
.assertThat()
.statusCode(200)
.contentType(ContentType.JSON)
.extract()
.path("token");
}
}
Test Steps:
Send a PATCH request to the endpoint https://booking-api-dev.herokuapp.com/booking/1 :
Request Method: PATCH
Headers:
Content-Type: application/json
Accept: application/json
Cookie: token=abc123 (replace with your actual token)
Request Body:
{
"firstname": "James",
"lastname": "Brown"
}
Expected Results:
Verify that the response status code is 200 OK.
Verify that the response content type is application/json.
Verify that the response body contains the updated booking details:
"firstname" should be equal to "James".
"lastname" should be equal to "Brown".
"totalprice" should not be null.
"depositpaid" should not be null.
"bookingdates.checkin" should not be null.
"bookingdates.checkout" should not be null.
"additionalneeds" should not be null.
import io.restassured.http.ContentType;
import org.junit.BeforeClass;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class PartialUpdateBooking {
private static final String BASE_URL = "https://booking-api-dev.herokuapp.com";
private static String TOKEN;
@BeforeClass
public static void setup() {
// Step 1: Obtain authentication token
TOKEN = obtainAuthToken("admin", "password123");
}
@Test
public void updateBookingWithPartialPayload() {
String bookingId = "1"; // Replace with the actual booking ID
given()
.baseUri(BASE_URL)
.basePath("/booking/{id}")
.pathParam("id", bookingId)
.header("Content-Type", ContentType.JSON.toString())
.header("Accept", ContentType.JSON.toString())
.header("Cookie", "token=" + TOKEN)
.body("{\n" +
" \"firstname\": \"James\",\n" +
" \"lastname\": \"Brown\"\n" +
"}")
.when()
.patch()
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("firstname", equalTo("James"))
.body("lastname", equalTo("Brown"))
.body("totalprice", notNullValue())
.body("depositpaid", notNullValue())
.body("bookingdates.checkin", notNullValue())
.body("bookingdates.checkout", notNullValue())
.body("additionalneeds", notNullValue());
}
private static String obtainAuthToken(String username, String password) {
// Step 2: Send a POST request to obtain authentication token
return given()
.baseUri(BASE_URL)
.basePath("/auth")
.header("Content-Type", ContentType.JSON.toString())
.header("Accept", ContentType.JSON.toString())
.body("{\n" +
" \"username\" : \"" + username + "\",\n" +
" \"password\" : \"" + password + "\"\n" +
"}")
.when()
.post()
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.extract()
.path("token");
}
}
Используя библиотеку REST Assured, напишите код для выполнения POST-запроса к эндпоинту https://booking-api-dev.herokuapp.com/auth, передавая JSON-параметры для аутентификации (username: "admin", password: "password123").
Дополнительные требования:
Задайте заголовок Content-Type со значением application/json..
Ожидается успешный ответ (HTTP/1.1 200 OK). .
Извлеките токен из ответа и сохраните его для использования в следующих запросах.
Используя полученный токен (из предыдущего задания), напишите код для выполнения PUT и DELETE запросов к эндпоинту https://booking-api-dev.herokuapp.com/booking.
Дополнительные требования:
Выберите произвольный идентификатор брони (bookingId).
Для PUT-запроса передайте обновленные данные брони в формате JSON.
Используя библиотеку REST Assured, напишите код для выполнения GET-запроса к эндпоинту https://booking-api-dev.herokuapp.com/booking с возможностью использования опциональных параметров запроса для фильтрации результатов.
Дополнительные требования:
.
Реализуйте три варианта GET-запросов, аналогичных примерам в описании:
Простой GET-запрос для получения всех идентификаторов броней..
GET-запрос с фильтрацией по имени (firstname)..
GET-запрос с фильтрацией по дате заезда (checkin) и дате выезда (checkout).
Используя библиотеку REST Assured, напишите код для выполнения POST-запроса к эндпоинту https://booking-api-dev.herokuapp.com/booking, создавая новую бронь с заданными параметрами.
Дополнительные требования:
Реализуйте три варианта POST-запросов, используя различные форматы payload (JS
ON, XML, URLencoded).
Ожидается успешный ответ (HTTP/1.1 200 OK).
Извлеките идентификатор созданной брони из ответа для дальнейшего использования.
Используя библиотеку REST Assured, напишите код для выполнения PUT-запроса к эндпоинту https://booking-api-dev.herokuapp.com/booking/:id для обновления существующей брони с заданными параметрами.
Дополнительные требования:
Реализуйте три варианта PUT-запросов, используя различные форматы payload (JSON, XML, URLencoded).
Добавьте заголовки Content-Type, Accept, и Cookie (для передачи токена авторизации) в запрос.
Ожидается успешный ответ (HTTP/1.1 200 OK) с обновленными данными брони.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class CreateBooking {
@Test
public void createBookingTest() {
// Set base URI and port
RestAssured.baseURI = "https://booking-api-dev.herokuapp.com";
RestAssured.port = 443; // Assuming the API uses HTTPS
// Request body JSON
String requestBody = "{\n" +
" \"firstname\" : \"Jim\",\n" +
" \"lastname\" : \"Brown\",\n" +
" \"totalprice\" : 111,\n" +
" \"depositpaid\" : true,\n" +
" \"bookingdates\" : {\n" +
" \"checkin\" : \"2018-01-01\",\n" +
" \"checkout\" : \"2019-01-01\"\n" +
" },\n" +
" \"additionalneeds\" : \"Breakfast\"\n" +
"}";
// Send POST request
String response =
given()
.header("Content-Type", ContentType.JSON)
.body(requestBody)
.when()
.post("/booking")
.then()
.statusCode(200)
.body("bookingid", notNullValue())
.body("booking.firstname", equalTo("Jim"))
.body("booking.lastname", equalTo("Brown"))
.body("booking.totalprice", equalTo(111))
.body("booking.depositpaid", equalTo(true))
.body("booking.bookingdates.checkin", equalTo("2018-01-01"))
.body("booking.bookingdates.checkout", equalTo("2019-01-01"))
.body("booking.additionalneeds", equalTo("Breakfast"))
.extract().asString();
System.out.println("Response: " + response);
// Additional assertions with detailed error messages
if (!response.contains("bookingid")) {
System.out.println("Assertion failed: 'bookingid' not found in response.");
}
if (!response.contains("Jjim")) {
System.out.println("Assertion failed: 'Jim' not found in response.");
}
if (!response.contains("Brown")) {
System.out.println("Assertion failed: 'Brown' not found in response.");
}
if (!response.contains("201j8-01-01")) {
System.out.println("Assertion failed: '2018-01-01' not found in response.");
}
}
}
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class CreateAssert {
@Test
public void createBookingTest() {
// Set base URI and port
RestAssured.baseURI = "https://booking-api-dev.herokuapp.com";
RestAssured.port = 443; // Assuming the API uses HTTPS
// Request body JSON
String requestBody = "{\n" +
" \"firstname\" : \"Jim\",\n" +
" \"lastname\" : \"Brown\",\n" +
" \"totalprice\" : 111,\n" +
" \"depositpaid\" : true,\n" +
" \"bookingdates\" : {\n" +
" \"checkin\" : \"2018-01-01\",\n" +
" \"checkout\" : \"2019-01-01\"\n" +
" },\n" +
" \"additionalneeds\" : \"Breakfast\"\n" +
"}";
// Send POST request
String response = null;
try {
response = given()
.header("Content-Type", ContentType.JSON)
.body(requestBody)
.when()
.post("/booking")
.then()
.statusCode(200)
.body("bookingid", notNullValue(), "Assertion failed: 'bookingid' not found in response.")
.body("booking.firstname", equalTo("Jim"), "Assertion failed: 'Jim' not found in response.")
.body("booking.lastname", equalTo("Brown"), "Assertion failed: 'Brown' not found in response.")
.body("booking.totalprice", equalTo(111), "Assertion failed: '111' not found in response.")
.body("booking.depositpaid", equalTo(true), "Assertion failed: 'true' not found in response.")
.body("booking.bookingdates.checkin", equalTo("2018-01-01"), "Assertion failed: '2018-01-01' not found in response.")
.body("booking.bookingdates.checkout", equalTo("2019-01-01"), "Assertion failed: '2019-01-01' not found in response.")
.body("booking.additionalneeds", equalTo("Breakfast"), "Assertion failed: 'Breakfast' not found in response.")
.extract().asString();
System.out.println("All assertions passed.");
} catch (AssertionError e) {
System.out.println("Assertion failed: " + e.getMessage());
} finally {
if (response != null) {
System.out.println("Response: " + response);
}
}
}
}
Хотите больше практики на проекте?
Использование REST Assured с Cucumber и Page Object паттерном может сделать ваш код более профессиональным и обеспечить лучшую читаемость, поддерживаемость и масштабируемость автоматизированных тестов.

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