Rest Assured

Rest Assured Automation Suite

Instalação, clients, schemas, segurança, OpenAPI e CI — 98 testes

Automação · Java 17 · Spring Petclinic REST

O que é o Rest Assured?

Biblioteca Java para testar APIs REST com DSL fluente — integra com JUnit 5, Hamcrest e Allure.

  • Sintaxe BDD: given() · when() · then()
  • Validação JSON com JsonPath e schemas
  • POJO mapping com Jackson
  • Filtros para logging e captura de rede

Stack do projeto

Java 17

Records, text blocks, modern language features.

Docker

API Petclinic + testes em containers isolados.

GitHub Actions

CI com service container e Allure no Pages.

Allure

@Epic, @Feature, @Story e anexos de rede.

Pré-requisitos

  • Java 17+ e Maven 3.9+
  • Docker (recomendado para API + testes)
  • IDE: IntelliJ, VS Code ou Cursor
docker compose up --abort-on-container-exit --exit-code-from tests
mvn clean test
mvn allure:serve

Estrutura do projeto

src/test/java/com/portfolio/petclinic/
├── base/       BaseTest — setup compartilhado
├── clients/    OwnersClient, PetsClient, ...
├── models/     POJOs de request/response
├── tests/      Suites JUnit 5
│   ├── advanced/
│   ├── flows/
│   └── negative/
└── utils/      ConfigLoader, TestDataFactory, validators

Client layer

public Response getAllOwners() {
    return given()
        .spec(requestSpec)
        .when()
        .get("/owners");
}

Specs nunca chamam RestAssured.given() diretamente — use clients.

Primeiro teste

@Test
void shouldReturnAllOwnersWithValidStructure() {
    Response response = ownersClient.getAllOwners();
    ResponseValidator.assertStatusCode(response.getStatusCode(), 200);
    ResponseValidator.assertFirstArrayItemMatchesSchema(
        response.getBody().asString(), "schemas/owner-schema.json");
}

Validação de schema

  • owner-schema.json — respostas de owner
  • pet-schema.json — respostas de pet
  • problem-detail-schema.json — erros RFC 7807

Schemas em src/test/resources/schemas/

Dados dinâmicos

Owner ownerPayload = TestDataFactory.buildOwner();
PetFields pet = TestDataFactory.buildPetFields(typeId, typeName);

JavaFaker evita colisões e dados fixos em paralelo.

Testes parametrizados

@ParameterizedTest(name = "GET /owners/{0} should return {1}")
@CsvSource({ "99999, 404", "0, 404" })
void shouldReturnExpectedStatusForInvalidOwnerIds(int id, int status) {
    Response response = ownersClient.getOwnerById(id);
    ErrorResponseValidator.assertErrorStatusAndOptionalProblemDetail(...);
}

Captura de rede

NetworkInspector.attachLastExchangeToAllure(networkCapture);
NetworkInspector.assertLastRequestUriContains(networkCapture, "/pets");
NetworkInspector.assertResponseSequenceContains(networkCapture, "/owners", "/pets/");

WireMock

  • Stub de webhook /audit/owner-created
  • WireMock.verify() com JSON exato
  • Resiliência: timeout, JSON inválido, connection reset
  • Retry após 503 com cenário WireMock

Cobertura — 98 testes

Domínio

Owners, Pets, Visits, Vets, Specialties, PetTypes, API v2.

Smoke

Actuator health + OpenAPI /v3/api-docs.

Segurança

Basic Auth, RBAC, POST /users na API :9967.

Avançado

SLA, integridade referencial, content negotiation.

Visits & recursos novos

visitsClient.addVisit(ownerId, petId, visitFields);
visitsClient.updateVisit(visitId, updatePayload);
ownersClient.getOwnerPetById(ownerId, petId);
ownersV2Client.getOwnersPage(0, 2, lastName);

Segurança dual-API

  • 9966 — API aberta (dev/Docker padrão)
  • 9967 — PETCLINIC_SECURITY_ENABLE=true
  • OwnersClient.secured() · withCredentials()
  • @Tag("security") para suite isolada

Tags JUnit

mvn test -Dtest.groups=smoke
mvn test -Dtest.groups=security
mvn test -Dtest.groups=performance
mvn test -Dtest.groups=contract

CI — GitHub Actions

  • Dois service containers: API padrão + API segura
  • Health check via Actuator
  • mvn clean test — 98 testes
  • Allure publicado no GitHub Pages em push para main

Documentação

Obrigado!

Execute a suite e explore os walkthroughs bloco a bloco.

github.com/lflucasferreira/rest-assured