Rest Assure Class Diagram - Notes By ShariqSP
Class Diagram
RequestSpecification
- Body()
- headerAuth()
- basePath()
- config()
- contentType()
- post()
- put()
- patch()
- delete()
- formParameter()
- pathParameter()
- queryParameter()
- param()
- spec()
RestAssured
- get()
- post()
- put()
- patch()
- delete()
- given()
- when()
- then()
- basic()
- certificate()
- auth()
- oauth2()
- authentication
- basePath()
- baseURI()
- port()
- proxy()
Response
- then()
- getContentType()
- getTime()
- getTimeIn()
- getSessionID()
- getCookies()
- getBody()
- getHeader()
- getStatusLine()
- jsonPath()
- xmlPath()
- htmlPath()
- prettyPrint()
- asString()
Explanation of the Class Diagram
The class diagram above represents the key components of the Rest Assured library used for API testing. Each class and its associated methods are described below in detail:
1. RequestSpecification
The RequestSpecification class is the foundation for building API requests. It allows you to define the structure, parameters, headers, body, and configuration of your request before sending it. This class provides various methods for customizing API requests, including:
- Body(): Sets the request payload (body).
- headerAuth(): Adds authentication headers.
- basePath(): Sets the base path of the API.
- config(): Configures various settings for the request.
- contentType(): Specifies the content type of the request (e.g., JSON).
- post(), put(), patch(), delete(): Specifies the HTTP method to be executed.
- formParameter(), pathParameter(), queryParameter(): Adds parameters to the request.
- param(): A shorthand for adding query parameters.
- spec(): Allows you to reuse a predefined request specification.
2. RestAssured
The RestAssured class acts as the entry point for API testing. It provides static methods to configure global settings, such as base URI, port, and authentication. It also includes methods to initiate API requests. Key methods include:
- get(), post(), put(), patch(), delete(): Methods to specify the HTTP verb for API calls.
- given(): Prepares the request by setting specifications like headers, body, etc.
- when(): Specifies the action to be performed (e.g., HTTP method).
- then(): Validates the response and asserts its content.
- basic(), certificate(), auth(), oauth2(), authentication: Provides various methods for authentication.
- basePath(), baseURI(), port(), proxy(): Configures global request properties such as API location and proxy details.
3. Response
The Response class represents the server's response to an API request. It provides methods to extract, validate, and manipulate the response data. Key methods include:
- then(): Begins the response validation process.
- getContentType(): Retrieves the content type of the response.
- getTime(), getTimeIn(): Measures the time taken for the response.
- getSessionID(): Extracts the session ID from the response.
- getCookies(), getBody(), getHeader(), getStatusLine(): Accesses various parts of the response.
- jsonPath(), xmlPath(), htmlPath(): Parses the response into JSON, XML, or HTML format.
- prettyPrint(), asString(): Formats and returns the response body as a string.
Relationships in the Diagram
The relationships between these classes highlight their interactions:
- RestAssured is the starting point and provides static methods to configure and initialize requests.
- RequestSpecification defines the request details such as headers, body, and parameters.
- Response handles the server's response and provides methods to validate and process it.
This design allows you to build, send, and validate API requests in a modular and structured way, ensuring comprehensive API testing.
Using Rest Assured Class Diagram Methods with Examples
The following examples demonstrate how to use the Rest Assured class diagram methods for API testing with the endpoints
/api/users/register
and /api/users/all
from the base URL
http://apitesting.shariqsp.com:8080
.
1. RequestSpecification Methods
The RequestSpecification methods are used to define the structure and content of API requests.
Example: Register a User RestAssured.given() .baseUri("http://apitesting.shariqsp.com:8080") // Setting the base URI .basePath("/api/users/register") // Defining the base path .contentType("application/json") // Setting the content type .body("{ \"name\": \"John Doe\", \"email\": \"john.doe@example.com\", \"password\": \"123456\" }") // Adding the request body .when() .post() // Executing a POST request .then() .statusCode(201) // Validating the status code .body("message", equalTo("User registered successfully")); // Validating the response body
2. RestAssured Methods
RestAssured provides static methods to configure and execute requests.
Example: Fetch All Users RestAssured.given() .baseUri("http://apitesting.shariqsp.com:8080") // Setting the base URI .basePath("/api/users/all") // Defining the base path .when() .get() // Executing a GET request .then() .statusCode(200) // Validating the status code .body("data.size()", greaterThan(0)); // Checking that users are returned
3. Response Methods
The Response methods handle and validate the server's response to an API request.
Example: Extract and Validate User Data Response response = RestAssured.given() .baseUri("http://apitesting.shariqsp.com:8080") // Setting the base URI .basePath("/api/users/all") // Defining the base path .when() .get(); // Executing a GET request // Validating response details response.then() .statusCode(200) // Checking the status code .contentType("application/json"); // Validating the content type // Extracting data from the response List
Combining Classes
The RequestSpecification, RestAssured, and Response classes work together seamlessly:
- RequestSpecification: Defines the request's structure, including headers, body, and query parameters.
- RestAssured: Executes the request and provides configuration options.
- Response: Processes and validates the response received from the server.
For example, in the user registration case, the request's body and headers are defined using RequestSpecification
. The post()
method from RestAssured
sends the request, and the Response
object is used to validate the results.
Validate Response Methods in Rest Assured
Validating the response is a crucial step in API testing. The Rest Assured library provides multiple methods to validate the structure, content, and performance of API responses. These methods can be used to ensure that the API behaves as expected, both functionally and performance-wise.
Key Methods for Response Validation
The following are the primary methods available in Rest Assured for validating responses:
- statusCode() - Validates the HTTP status code of the response.
- statusLine() - Validates the HTTP status line.
- contentType() - Validates the content type of the response.
- body() - Validates specific parts of the response body using JSONPath or XMLPath.
- time() - Validates the time taken for the response.
- header() - Validates the presence or value of a specific header in the response.
- cookie() - Validates the presence or value of a specific cookie in the response.
1. statusCode()
The statusCode()
method checks if the response's status code matches the expected value. Common status codes include 200 (OK), 201 (Created), and 404 (Not Found).
Example: RestAssured.given() .when() .get("/api/users") .then() .statusCode(200); // Validates that the response status code is 200
2. statusLine()
The statusLine()
method validates the HTTP status line, which includes the protocol, status code, and status message.
Example: RestAssured.given() .when() .get("/api/users") .then() .statusLine("HTTP/1.1 200 OK"); // Validates the exact status line
3. contentType()
This method ensures that the response has the expected content type, such as application/json
or text/html
.
Example: RestAssured.given() .when() .get("/api/users") .then() .contentType("application/json"); // Validates that the response content type is JSON
4. body()
The body()
method is used to validate specific parts of the response body using JSONPath or XMLPath. It can also check nested objects and arrays.
Example: RestAssured.given() .when() .get("/api/users") .then() .body("data[0].name", equalTo("John Doe")); // Validates that the first user's name is "John Doe"
5. time()
This method validates the time taken for the response, ensuring that it is within acceptable limits.
Example: RestAssured.given() .when() .get("/api/users") .then() .time(lessThan(2000L)); // Validates that the response time is less than 2000 milliseconds
6. header()
The header()
method validates the value of a specific header in the response.
Example: RestAssured.given() .when() .get("/api/users") .then() .header("Content-Type", "application/json"); // Validates that the Content-Type header is "application/json"
7. cookie()
This method validates the value or presence of a cookie in the response.
Example: RestAssured.given() .when() .get("/api/users") .then() .cookie("SESSIONID", notNullValue()); // Validates that the SESSIONID cookie is present
Using Multiple Validation Methods Together
Rest Assured allows chaining multiple validation methods to comprehensively validate the response.
Example: RestAssured.given() .when() .get("/api/users") .then() .statusCode(200) // Validates status code .contentType("application/json") // Validates content type .body("data.size()", greaterThan(0)) // Validates that the response contains data .time(lessThan(2000L)); // Validates response time
Expanded Documentation for Rest Assured Classes
1. RequestSpecification Class Methods
The RequestSpecification
class provides methods for defining HTTP request details. Below are additional methods:
log().all()
Logs all the details of the request, including headers, parameters, and the body, for debugging purposes.
RestAssured.given()
.baseUri("http://example.com")
.log().all() // Logs the entire request details
.when()
.get();
assertThat()
A fluent assertion method to validate specific properties of the request. Often used in combination with then()
.
RestAssured.given()
.baseUri("http://example.com")
.when()
.get()
.then()
.assertThat()
.statusCode(200) // Asserts that the response code is 200
.contentType("application/json"); // Asserts the content type
log().ifValidationFails()
Logs request details only if the validation fails. This is useful for debugging failed tests.
RestAssured.given()
.baseUri("http://example.com")
.log().ifValidationFails()
.when()
.get()
.then()
.statusCode(404); // Logs details only if the status code is not 404
2. Response Class Methods
The Response
class offers methods to validate and extract details from the server response.
assertThat()
Validates specific properties of the response, such as status codes, headers, or body content.
Response response = RestAssured.given()
.baseUri("http://example.com")
.when()
.get();
response.then().assertThat().statusCode(200).body("message", equalTo("Success"));
log().all()
Logs the entire response details for debugging purposes.
Response response = RestAssured.given()
.baseUri("http://example.com")
.when()
.get();
response.then().log().all(); // Logs headers, body, etc.
log().ifValidationFails()
Logs the response details only if validation fails.
response.then()
.log().ifValidationFails()
.statusCode(200); // Logs only if the response code is not 200
asPrettyString()
Similar to prettyPrint()
, but it returns the response as a formatted string rather than printing it.
String responseBody = response.then().asPrettyString();
System.out.println(responseBody);
asByteArray()
Returns the response body as a byte array, useful for handling binary data.
byte[] data = response.asByteArray();
extract()
Extracts specific parts of the response, such as headers or body elements, for further validation.
String token = response.then().extract().path("token");
System.out.println("Extracted Token: " + token);
3. Combining Logging and Validation in Requests
Using these methods together enhances test clarity and debugging.
RestAssured.given()
.baseUri("http://example.com")
.log().all() // Logs request details
.when()
.get()
.then()
.log().ifValidationFails() // Logs response only if validation fails
.statusCode(200)
.assertThat()
.body("status", equalTo("Success"));
4. Updated Features in Class Diagram
RequestSpecification (Extended)
log().all()
log().ifValidationFails()
assertThat()
Response (Extended)
log().all()
log().ifValidationFails()
asPrettyString()
asByteArray()
extract()