REST Assured.Day 2

Продолжаем изучать документацию
Пишем тест-кейсы
Покрываем автотестами создание и  редактирование бронирования

 

Документация по REST API

Перед началом написания тестов необходимо тщательно изучить документацию по REST API. Без этого этапа невозможно составить тест-кейсы, которые охватывают бы все сценарии использования. В документации вы найдете все необходимые эндпоинты, методы запросов, параметры и ожидаемые ответы. Это позволит вам глубоко понять, как взаимодействовать с API, и убедиться, что ваши тесты будут полноценно покрывать функциональность, исключая ошибки в работе.

Составление тест-кейсов по созданию бронирования

Шаги:

Отправить POST-запрос на эндпоинт /booking с предоставленным телом запроса.

Ожидаемый результат:

    • Убедиться, что ответ соответствует схеме, указанной в файле “bookingCreateResponseSchema.json”.

JSON  файл https://drive.google.com/file/d/1XqDr83yj2XJ5GElKm_QSSmmbpf3fgIr0/view?usp=sharing

Шаги:

Отправить POST-запрос на эндпоинт /booking с предоставленным телом запроса.

Ожидаемый результат:

    • Код состояния ответа должен быть 200 (OK).

Проверка времени ответа на создание бронирования менее 3000 мс

Шаги:

Отправить POST-запрос на эндпоинт /booking с предоставленным телом запроса.

Ожидаемый результат:

      • Время ответа должно быть менее 3000 мс.

Шаги:

Отправить POST-запрос на эндпоинт /booking с предоставленным телом запроса.

Ожидаемый результат:

    • Значение поля “firstname” в теле ответа должно быть “Jim”.

Написание автотеста по тест-кейсам с комментариями

package activities;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;


public class CreateActivities {
private String baseUrl = “https://restful-booker.herokuapp.com”; // Base URL for the API
private String basePath = “/booking”; // Base path

/**
* Test to verify that the created booking matches the schema
*/
@Test
@DisplayName(“Create Booking matches schema”)
public void test1() {

// Arrange
String body = “””
{
“firstname” : “Jim”, // Customer’s first name
“lastname” : “Brown”, // Customer’s last name
“totalprice” : 111, // Total price of the booking
“depositpaid” : true, // Flag indicating whether deposit is paid
“bookingdates” : { // Booking dates
“checkin” : “2018-01-01”, // Check-in date
“checkout” : “2019-01-01” // Checkout date
},
“additionalneeds” : “Breakfast” // Customer’s additional needs
}
“””;

// Act
ValidatableResponse response = RestAssured
.given() // Start forming the request
.basePath(basePath) // Set the base path
.baseUri(baseUrl) // Set the base URL
.contentType(ContentType.JSON) // Set the content type (JSON)
.body(body) // Set the request body
.when() // Finish forming the request and proceed to execution
.post() // Send a POST request
.then(); // Finish the request and proceed to checks

// Assert
response.assertThat().body(matchesJsonSchemaInClasspath(“bookingCreateResponseSchema.json”)); // Verify that the response matches the schema
}

/**
* Test to verify that creating a booking returns a status code of 200
*/
@Test
@DisplayName(“Create Booking has 200 status code”)
public void test2() {

// Arrange
String body = “””
{
“firstname” : “Jim”, // Customer’s first name
“lastname” : “Brown”, // Customer’s last name
“totalprice” : 111, // Total price of the booking
“depositpaid” : true, // Flag indicating whether deposit is paid
“bookingdates” : { // Booking dates
“checkin” : “2018-01-01”, // Check-in date
“checkout” : “2019-01-01” // Checkout date
},
“additionalneeds” : “Breakfast” // Customer’s additional needs
}
“””;

// Act
ValidatableResponse response = RestAssured
.given() // Start forming the request
.basePath(basePath) // Set the base path
.baseUri(baseUrl) // Set the base URL
.contentType(ContentType.JSON) // Set the content type (JSON)
.body(body) // Set the request body
.when() // Finish forming the request and proceed to execution
.post() // Send a POST request
.then(); // Finish the request and proceed to checks

// Assert
response.assertThat().statusCode(200); // Verify that the response status code is 200
}

/**
* Test to verify that the response time for creating a booking is less than 3000ms
*/
@Test
@DisplayName(“Create Booking has response less than 3000ms”)
public void test3() {

// Arrange
String body = “””
{
“firstname” : “Jim”, // Customer’s first name
“lastname” : “Brown”, // Customer’s last name
“totalprice” : 111, // Total price of the booking
“depositpaid” : true, // Flag indicating whether deposit is paid
“bookingdates” : { // Booking dates
“checkin” : “2018-01-01”, // Check-in date
“checkout” : “2019-01-01” // Checkout date
},
“additionalneeds” : “Breakfast” // Customer’s additional needs
}
“””;

// Act
ValidatableResponse response = RestAssured
.given() // Start forming the request
.basePath(basePath) // Set the base path
.baseUri(baseUrl) // Set the base URL
.contentType(ContentType.JSON) // Set the content type (JSON)
.body(body) // Set the request body
.when() // Finish forming the request and proceed to execution
.post() // Send a POST request
.then(); // Finish the request and proceed to checks

// Assert
response.assertThat().time(lessThan(3000L)); // Verify that the response time is less than 3000ms
}

/**
* Test to verify that the booking field has the correct value
*/
@Test
@DisplayName(“Create Booking field has value”)
public void test4() {

// Arrange
String body = “””
{
“firstname” : “Jim”, // Customer’s first name
“lastname” : “Brown”, // Customer’s last name
“totalprice” : 111, // Total price of the booking
“depositpaid” : true, // Flag indicating whether deposit is paid
“bookingdates” : { // Booking dates
“checkin” : “2018-01-01”, // Check-in date
“checkout” : “2019-01-01” // Checkout date
},
“additionalneeds” : “Breakfast” // Customer’s additional needs
}
“””;

// Act
ValidatableResponse response = RestAssured
.given() // Start forming the request
.basePath(basePath) // Set the base path
.baseUri(baseUrl) // Set the base URL
.contentType(ContentType.JSON) // Set the content type (JSON)
.body(body) // Set the request body
.log().all() // Log the request
.when() // Finish forming the request and proceed to execution
.post() // Send a POST request
.then() // Finish the request and proceed to checks
.log().all(); // Log the response

// Assert
response.assertThat().body(“booking.firstname”, equalTo(“Jim”)); // Verify that the “firstname” field has the value “Jim”
}
}

Составление тест-кейсов по редактированию бронирования

Шаги:

Подготовка запроса с обновлением всех полей бронирования:

    • firstname: “Jimmy”
    • lastname: “Brown”
    • totalprice: 222
    • depositpaid: true
    • bookingdates:
      • checkin: “2018-01-01”
      • checkout: “2019-01-02”
    • additionalneeds: “Breakfast”

Отправка запроса на обновление бронирования.

Проверка: Убедиться, что ответ соответствует схеме “bookingGetResponseSchema.json”.

JSON  файл https://drive.google.com/file/d/1XqDr83yj2XJ5GElKm_QSSmmbpf3fgIr0/view?usp=sharing

Шаги:

Подготовка запроса с частичным обновлением полей бронирования:

    • firstname: “Jimmy”
    • lastname: “Brown”

Отправка запроса на частичное обновление бронирования.

Проверка: Убедиться, что ответ соответствует схеме “bookingGetResponseSchema.json”.

JSON  файл https://drive.google.com/file/d/1XqDr83yj2XJ5GElKm_QSSmmbpf3fgIr0/view?usp=sharing

Написание автотеста по тест-кейсам с комментариями

package activities;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.*;

import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;


public class EditActivities {
private static String baseUrl = “https://restful-booker.herokuapp.com”;
private static String basePath = “/booking”;
private static String token;
private String id = “/” + 88;

// Obtaining the authentication token before running the tests
@BeforeAll
public static void getToken() {
String authPath = “/auth”;

// Authentication body
String body = “””
{
“username” : “admin”,
“password” : “password123”
}
“””;

// Sending a request to get the token
token = RestAssured // Assigning the token
.given() // Starting the REST Assured request
.baseUri(baseUrl) // Setting the base URI
.basePath(authPath) // Setting the base path
.contentType(ContentType.JSON) // Setting the content type as JSON
.body(body) // Setting the body of the request
.log().all() // Logging the request
.when() // Starting the HTTP request
.post() // Sending a POST request
.then() // Assertion part of the request
.log().all() // Logging the response
.extract().jsonPath().getJsonObject(“token”); // Extracting the token from the response body
}

@Test
@DisplayName(“Response in ‘Update All Booking fields’ method matches schema”)
public void test1() {
// Preparation
String body = “””
{
“firstname” : “Jimmy”,
“lastname” : “Brown”,
“totalprice” : 222,
“depositpaid” : true,
“bookingdates” : {
“checkin” : “2018-01-01”,
“checkout” : “2019-01-02”
},
“additionalneeds” : “Breakfast”
}
“””;

// Action: Updating all booking fields
ValidatableResponse response = RestAssured // Assigning the response
.given() // Starting the REST Assured request
.baseUri(baseUrl) // Setting the base URI
.basePath(basePath + id) // Setting the base path with the booking ID
.header(“Accept”, “application/json”) // Adding an accept header
.header(“Cookie”, “token=” + token) // Adding the authentication token to the header
.contentType(ContentType.JSON) // Setting the content type as JSON
.body(body) // Setting the body of the request
.log().all() // Logging the request
.when() // Starting the HTTP request
.put() // Sending a PUT request
.then() // Assertion part of the request
.log().all(); // Logging the response

// Assertion: Verify that the response matches the schema
response.assertThat().body(matchesJsonSchemaInClasspath(“bookingGetResponseSchema.json”));
}

@Test
@DisplayName(“Response in ‘Partial Update Booking fields’ method matches schema”)
public void test2() {
// Preparation
String body = “””
{
“firstname” : “Jimmy”,
“lastname” : “Brown”
}
“””;

// Action: Partially updating booking fields
ValidatableResponse response = RestAssured // Assigning the response
.given() // Starting the REST Assured request
.baseUri(baseUrl) // Setting the base URI
.basePath(basePath + id) // Setting the base path with the booking ID
.header(“Accept”, “application/json”) // Adding an accept header
.header(“Cookie”, “token=” + token) // Adding the authentication token to the header
.contentType(ContentType.JSON) // Setting the content type as JSON
.body(body) // Setting the body of the request
.log().all() // Logging the request
.when() // Starting the HTTP request
.patch() // Sending a PATCH request
.then() // Assertion part of the request
.log().all(); // Logging the response

// Assertion: Verify that the response matches the schema
response.assertThat().body(matchesJsonSchemaInClasspath(“bookingGetResponseSchema.json”));
}

@Test
@DisplayName(“Delete Booking”)
public void test3() {
// Action: Deleting a booking
ValidatableResponse response = RestAssured // Assigning the response
.given() // Starting the REST Assured request
.baseUri(baseUrl) // Setting the base URI
.basePath(basePath + id) // Setting the base path with the booking ID
.header(“Accept”, “application/json”) // Adding an accept header
.header(“Cookie”, “token=” + token) // Adding the authentication token to the header
.contentType(ContentType.JSON) // Setting the content type as JSON
.log().all() // Logging the request
.when() // Starting the HTTP request
.delete() // Sending a DELETE request
.then() // Assertion part of the request
.log().all(); // Logging the response

// Assertion: Verify that the response status code is 201 (Created)
response.assertThat().statusCode(201);
}

// Performing cleanup after all tests
@AfterAll
public static void tearDown() {
System.gc();
}
}

Самостоятельная работа

  • Изучить документацию
  • Дописать тест-кейсы по созданию и редактированию бронирования
  • Дописать автотесты

Расширенные инструменты REST Assured

Фильтры (Filters)

REST Assured позволяет применять фильтры для запросов и ответов, что дает возможность манипулировать данными до или после выполнения запроса. Фильтры могут быть использованы для логирования, аутентификации, логирования запросов и ответов и других задач.

Пример использования фильтров:

public class CustomLogFilter implements Filter {
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
System.out.println(“Request: ” + requestSpec.getMethod() + ” ” + requestSpec.getURI());
Response response = ctx.next(requestSpec, responseSpec);
System.out.println(“Response: ” + response.getStatusCode());
return response;
}
}

@Test
public void testWithCustomLogFilter() {
RestAssured
.filters(new CustomLogFilter())
.get(“/resource”)
.then()
.statusCode(200);
}

 

Сессии (Sessions)

REST Assured позволяет работать с сессиями, что особенно полезно в случае необходимости сохранения состояния между запросами, например, при авторизации.

Пример использования сессий:

@Test
public void testWithSession() {
SessionFilter sessionFilter = new SessionFilter();


given().
filter(sessionFilter).
param(“username”, “user”).
param(“password”, “password”).
when().
post(“/login”).
then().
assertThat().
statusCode(200);


given().
filter(sessionFilter).
when().
get(“/user”).
then().
assertThat().
statusCode(200);
}

Логирование (Logging)

REST Assured предоставляет возможность логирования запросов и ответов, что облегчает отладку и анализ.

Пример настройки логирования:
RestAssured
.given()
.log().all()
.when()
.get(“/resource”)
.then()
.log().all()
.statusCode(200);

Спецификация и конфигурация (Specification & Configuration)

REST Assured позволяет создавать спецификации и конфигурации, что упрощает и стандартизирует тесты. Это делает ваш код более чистым и модульным.

Пример использования спецификаций и конфигураций:

RequestSpecification requestSpec = new RequestSpecBuilder()
.setBaseUri(“http://api.example.com”)
.setContentType(ContentType.JSON)
.addHeader(“Authorization”, “Bearer token”)
.build();

ResponseSpecification responseSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.build();

@Test
public void testWithSpec() {
given().
spec(requestSpec).
when().
get(“/resource”).
then().
spec(responseSpec);
}

Сериализация и десериализация (Serialization & Deserialization)

REST Assured предоставляет возможность автоматической сериализации и десериализации объектов, что упрощает взаимодействие с телом запроса и ответа.

Пример сериализации и десериализации:
MyObject myObject = new MyObject();
myObject.setName(“John”);
myObject.setAge(30);

given().
contentType(“application/json”).
body(myObject).
when().
post(“/resource”).
then().
statusCode(200);


MyObject responseObject = given().
contentType(“application/json”).
when().
get(“/resource”).
as(MyObject.class);

assertThat(responseObject.getName(), equalTo(“John”));
assertThat(responseObject.getAge(), equalTo(30));

Использование паттернов проектирования

REST Assured хорошо интегрируется с различными паттернами проектирования, такими как Page Object Pattern или Screenplay Pattern, что позволяет упростить тестирование и сделать его более поддерживаемым и модульным.

Пример использования Page Object Pattern

public class APIPage {
private RequestSpecification requestSpec;

public APIPage(RequestSpecification requestSpec) {
this.requestSpec = requestSpec;
}

public Response getResource() {
return given()
.spec(requestSpec)
.when()
.get(“/resource”);
}
}

@Test
public void testWithPageObjectPattern() {
APIPage apiPage = new APIPage(requestSpec);
Response response = apiPage.getResource();

response.then().statusCode(200);
}

Интеграция с Cucumber

Cucumber – это инструмент для автоматизированного тестирования, который использует язык Gherkin для написания тестовых сценариев в формате “Когда-Тогда-Если”. REST Assured может быть легко интегрирован с Cucumber для написания более понятных тестов.

Feature: API Testing
Scenario: Verify resource endpoint
Given the base URI is “http://api.example.com”
When a GET request is sent to “/resource”
Then the response status code should be 200

И сам код

public class StepDefinitions {
private RequestSpecification requestSpec;
private Response response;

@Given(“the base URI is {string}”)
public void setBaseURI(String baseURI) {
requestSpec = new RequestSpecBuilder()
.setBaseUri(baseURI)
.build();
}

@When(“a GET request is sent to {string}”)
public void sendGetRequest(String endpoint) {
response = given()
.spec(requestSpec)
.when()
.get(endpoint);
}

@Then(“the response status code should be {int}”)
public void verifyStatusCode(int expectedStatusCode) {
response.then().statusCode(expectedStatusCode);
}
}

Месячный

Практикум по REST Assured

Прохождение полноценного курса по REST Assured поможет вам стать экспертом в тестировании REST API на языке Java и эффективно использовать все возможности этой мощной библиотеки для автоматизации тестирования вашего приложения.

Поддержка и вопросы

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

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

Отправка задания

После завершения написания тестов, пожалуйста, архивируйте ваш проект в формате ZIP или RAR и отправьте нам для проверки.









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

    Курсы

    Публичная оферта. Авторское право © 2024 Школа подготовки тестировщиков