REST Assured

Вступ до REST Assured

REST Assured - це бібліотека для тестування REST API на мові Java. Вона надає зручні засоби для створення та виконання HTTP-запитів до вашого API, а також перевірки відповідей на відповідність очікуваним результатам.

Основи REST API

REST (Representational State Transfer)

REST – це стиль архітектури програмного забезпечення, заснований на принципах, описаних у доповіді Роя Філдінга у 2000 році. Він надає легковажний та гнучкий спосіб створення веб-сервісів.

Ресурс

У REST дані представлені як ресурси, які можуть бути представлені у вигляді URL-адрес. Ресурси – це ключові сутності вашої програми, наприклад, користувачі, продукти чи замовлення.

HTTP-методи

Отримання даних із ресурсу. POST: Створення нового ресурсу. PUT: Оновлення наявного ресурсу. DELETE: Видалення ресурсу.

HTTP-статуси

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’

Встановлення та налаштування REST Assured

Крок 1: Встановлення IntelliJ IDEA

  1. Скачайте IntelliJ IDEA:
  2. Встановіть IntelliJ IDEA:
    • Запустіть інсталятор і дотримуйтесь інструкцій.

Крок 2: Створення проєкту

  1. Запустіть IntelliJ IDEA:
    • Відкрийте IntelliJ IDEA після інсталяції.
  2. Створіть новий проєкт:
    • Виберіть Create New Project і виберіть тип проєкту Maven.

Крок 3: Додавання залежностей Maven

  1. Відкрийте файл pom.xml:
    • У новому проєкті відкрийте файл pom.xml.
  2. Додайте залежність для проєкту:

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

Крок 4: Оновлення проєкту

  1. Оновіть проєкт:
    • У верхній частині IntelliJ IDEA ви побачите спливаюче повідомлення про необхідність оновлення проєкту. Натисніть "Import Changes".

Auth | CreateToken

  • Тест-кейс: Створення токена аутентифікації

    Кроки:
    Надіслати POST-запит створення токена аутентифікації до ендпоинту /auth.
    {
    "username": "admin",
    "password": "password123"
    }

    Перевірити, чи відповідь на запит має статус код 200 (OK).
    Перевірити, чи є у відповіді непустий параметр "token".
    Перевірити, чи параметр "token" відповідає очікуваному значенню "abc123"
    Виміряти час виконання запиту та переконатися, що воно знаходиться в розумних межах.
    Expected result:
    Токен аутентифікації успішно створено, і його значення відповідає очікуваному. Час виконання запиту перебуває у межах розумних значень.

Код

				
					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()<br>
                .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»);
Тут вимірюється час виконання запиту та виводяться результати, включаючи отриманий токен та час виконання запиту.

Booking | GetBookingIds

  • Тест-кейс: Отримання всіх ідентифікаторів бронювання

    Кроки:
    Надіслати 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).
    Expected result:
    Усі перевірки пройдено успішно, тест вважається успішним.

Код

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

				
			

Booking | GetBooking

  • Тест-кейс: Отримання даних бронювання за ID

    Кроки:
    Виконати GET-запит до "/booking/{id}" із зазначеним ID бронювання.
    Встановити заголовок "Accept" зі значенням "application/json".

    Expected result:
    Перевірити, чи код стану відповіді дорівнює 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);
    }
}
				
			

Booking | CreateBooking

  • Test Case: Create a New Booking

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

Booking | UpdateBooking

  • Test Case: Update Booking

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

Booking | PartialUpdateBooking

  • Test Case: Update Booking with partial payload

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

Завдання

Завдання 1

Використовуючи бібліотеку REST Assured, напишіть код для виконання POST-запиту до ендпоінту https://booking-api-dev.herokuapp.com/auth, передаючи JSON-параметри для автентифікації (username: "admin", password: "password123").
Додаткові вимоги:
Вкажіть заголовок Content-Type зі значенням application/json.
Очікується успішна відповідь (HTTP/1.1 200 OK).
Отримайте токен із відповіді та збережіть його для використання в наступних запитах.

Завдання 2

Використовуючи отриманий токен (з попереднього завдання), напишіть код для виконання PUT та DELETE запитів до ендпоінту https://booking-api-dev.herokuapp.com/booking.
Додаткові вимоги:
Виберіть довільний ідентифікатор броні (bookingId).
Для запиту PUT передайте оновлені дані броні у форматі JSON.

Завдання 3

Використовуючи бібліотеку REST Assured, напишіть код для виконання GET-запиту до ендпоінту https://booking-api-dev.herokuapp.com/booking із можливістю використання опціональних параметрів запиту для фільтрації результатів.
Дополнительные требования: .
Реалізуйте три варіанти GET-запитів:
Простий GET-запит для отримання всіх ідентифікаторів броней.
GET-запит з фільтрацією на ім'я (firstname).
GET-запит з фільтрацією за датою заїзду (checkin) та датою виїзду (checkout).

Завдання 4

Використовуючи бібліотеку REST Assured, напишіть код для виконання POST-запиту до ендпоінту https://booking-api-dev.herokuapp.com/booking, створюючи нову броню із заданими параметрами.
Додаткові вимоги:
Реалізуйте три варіанти POST-запитів за допомогою різних форматів payload (JSON, XML, URLencoded). Очікується успішна відповідь (HTTP/1.1 200 OK).
ON, XML, URLencoded). Ожидается успешный ответ (HTTP/1.1 200 OK).
Отримайте ідентифікатор броні з відповіді для подальшого використання.

Завдання 5

Використовуючи бібліотеку 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) з оновленими даними броні.

Додатковий код

If-Else | Create booking

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

				
			

Try-Catch | Create booking

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

				
			

Допишіть код для покриття інших функцій

Скиньте посилання на свій github для перевірки

Але це лише початок

Бажаєте більше практики на проекті? 

Використання REST Assured з Cucumber та Page Object патерном може зробити ваш код більш професійним та забезпечити кращу читаність, підтримуваність та масштабованість автоматизованих тестів.

Підтримка та питання

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

Через чат-бот