REST Assured Cheatsheet¶
Installazione¶
Maven Installation (pom.xml)¶
<dependencies>
<!-- Core REST Assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<!-- JSON Schema Validation -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<!-- JSON Path -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>5.4.0</version>
</dependency>
<!-- XML Path -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>5.4.0</version>
</dependency>
</dependencies>
Installazione del grado (build.gradle)¶
dependencies {
testImplementation 'io.rest-assured:rest-assured:5.4.0'
testImplementation 'io.rest-assured:json-schema-validator:5.4.0'
testImplementation 'io.rest-assured:json-path:5.4.0'
testImplementation 'io.rest-assured:xml-path:5.4.0'
}
Platform-Specific Prerequisiti¶
Tabella_168_
Importazioni richieste¶
// Static imports for fluent API
import static io.rest-assured.RestAssured.*;
import static io.rest-assured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
// Additional imports
import io.rest-assured.response.Response;
import io.rest-assured.specification.RequestSpecification;
import io.rest-assured.http.ContentType;
Basic HTTP Metodi¶
Tabella_169
Richiesta specifica¶
Tabella_170_
Validazione della risposta¶
TABELLA 171_
JSON Path Validation¶
Tabella_172_
Estrazione risposta¶
TABELLA 173_
Autenticazione avanzata¶
Tabella_174_
Richiesta specifiche (Riutilizzabile)¶
Traduzione: Tabella_175_
Specifiche di risposta (Reusable)¶
Traduzione: Tabella_176_
Logging¶
Tabella_177_
JSON Schema Validation¶
Traduzione: Tabella_178_
Convalida del percorso XML¶
Tabella_179_
Multipart/Form Data¶
Traduzione: Tabella_180_
Filtri (Richiesta/Risposta Intercettatori)¶
Traduzione: Tabella_181_
Configurazione¶
Configurazione globale¶
Traduzione: Tabella_182_
Configurazione SSL/TLS¶
Traduzione: Tabella_183_
Common Use Cases¶
Use Case 1: Semplice GET Richiesta con Validazione¶
import static io.rest-assured.RestAssured.*;
import static org.hamcrest.Matchers.*;
@Test
public void testGetUser() {
given()
.pathParam("id", 1)
.when()
.get("https://jsonplaceholder.typicode.com/users/{id}")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("id", equalTo(1))
.body("name", notNullValue())
.body("email", containsString("@"));
}
Use Case 2: POST Request with JSON Body and Extraction¶
@Test
public void testCreateUser() {
// Create user object
Map<String, String> user = new HashMap<>();
user.put("name", "John Doe");
user.put("email", "john@example.com");
// Send POST and extract ID
int userId = given()
.contentType(ContentType.JSON)
.body(user)
.when()
.post("https://api.example.com/users")
.then()
.statusCode(201)
.body("name", equalTo("John Doe"))
.body("email", equalTo("john@example.com"))
.extract()
.path("id");
System.out.println("Created user ID: " + userId);
}
Use Case 3: Authentication and Reusable Specifications¶
public class ApiTest {
private static RequestSpecification requestSpec;
private static ResponseSpecification responseSpec;
@BeforeClass
public static void setup() {
// Reusable request specification
requestSpec = new RequestSpecBuilder()
.setBaseUri("https://api.example.com")
.setBasePath("/v1")
.addHeader("Authorization", "Bearer " + getToken())
.setContentType(ContentType.JSON)
.build();
// Reusable response specification
responseSpec = new ResponseSpecBuilder()
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(2000L))
.build();
}
@Test
public void testGetUsers() {
given()
.spec(requestSpec)
.queryParam("page", 1)
.when()
.get("/users")
.then()
.spec(responseSpec)
.statusCode(200)
.body("data.size()", greaterThan(0));
}
private static String getToken() {
return given()
.contentType(ContentType.JSON)
.body("{\"username\":\"admin\",\"password\":\"secret\"}")
.when()
.post("https://api.example.com/auth/login")
.then()
.statusCode(200)
.extract()
.path("token");
}
}
Use Case 4: Carica file con Multipart¶
@Test
public void testFileUpload() {
File file = new File("src/test/resources/test-document.pdf");
given()
.multiPart("file", file, "application/pdf")
.multiPart("description", "Test document")
.multiPart("category", "reports")
.when()
.post("https://api.example.com/upload")
.then()
.statusCode(200)
.body("filename", equalTo("test-document.pdf"))
.body("size", greaterThan(0))
.body("status", equalTo("uploaded"));
}
Use Case 5: Complex JSON Validazione con JsonPath¶
@Test
public void testComplexJsonValidation() {
given()
.queryParam("page", 1)
.when()
.get("https://api.example.com/products")
.then()
.statusCode(200)
// Validate array size
.body("products.size()", equalTo(10))
// Validate nested fields
.body("products[0].name", notNullValue())
.body("products[0].price.amount", greaterThan(0f))
.body("products[0].price.currency", equalTo("USD"))
// Validate all items in array
.body("products.findAll { it.price.amount > 100 }.size()", greaterThan(0))
// Validate specific item
.body("products.find { it.id == 'PROD-123' }.name", equalTo("Widget"))
// Validate collection properties
.body("products*.category", hasItems("Electronics", "Books"));
}
Use Case 6: Response Deserialization to POJO¶
// User POJO class
public class User {
private int id;
private String name;
private String email;
// Getters and setters
}
@Test
public void testResponseDeserialization() {
// Extract as single object
User user = given()
.pathParam("id", 1)
.when()
.get("https://api.example.com/users/{id}")
.then()
.statusCode(200)
.extract()
.as(User.class);
Assert.assertEquals(1, user.getId());
Assert.assertNotNull(user.getName());
// Extract as list of objects
List<User> users = given()
.when()
.get("https://api.example.com/users")
.then()
.statusCode(200)
.extract()
.jsonPath()
.getList("data", User.class);
Assert.assertTrue(users.size() > 0);
}
Use Case 7: JSON Schema Validation¶
// user-schema.json in src/test/resources
/*
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"},
"email": {"type": "string", "format": "email"}
},
"required": ["id", "name", "email"]
}
*/
@Test
public void testJsonSchemaValidation() {
given()
.pathParam("id", 1)
.when()
.get("https://api.example.com/users/{id}")
.then()
.statusCode(200)
.assertThat()
.body(matchesJsonSchemaInClasspath("user-schema.json"));
}
Migliori Pratiche¶
- ** Utilizzare le importazioni statiche per la leggibilità**
- Import
io.rest-assured.RestAssured.*e __INLINE_CODE_160_ statically per il codice di prova più pulito e leggibile - La sintassi di Given-When-Then diventa più naturale e simile a BDD