Rest Assured 100+ Commands
Advanced & Framework Level
A dynamic, search-optimized cheat sheet for backend test engineers. Master REST-Assured payload mapping, header injection, security validations, database transaction rollbacks via JDBC, and server mocks using WireMock.
Hybrid API + UI Verification Track
Seamlessly connect back-end database audits with RESTful endpoint calls and Selenium/Playwright UI actions to design robust E2E validation frameworks.
Standard GET Request
Dispatches a basic HTTP GET request to the target resource and captures the complete server response envelope.
Response response = RestAssured.get("https://api.careerraah.com/v1/users");GET Request with Path Parameter
Binds a named path variable dynamically into the endpoint URI string during dispatch execution.
Response response = RestAssured
.given()
.pathParam("userId", "1024")
.when()
.get("https://api.careerraah.com/v1/users/{userId}");Pro-Tip: You can chain multiple pathParam() calls or use pathParams() with a map for cleaner multi-parameter syntax!
GET Request with Query Parameters
Appends standard URL search query parameters (e.g., ?role=admin&status=active) to the request payload destination.
Response response = RestAssured
.given()
.queryParam("role", "admin")
.queryParam("status", "active")
.when()
.get("https://api.careerraah.com/v1/users");POST Request with JSON String Body
Submits a resource creation request utilizing a raw serialized JSON string as the request payload.
String payload = "{\"name\":\"Jane\",\"email\":\"jane@example.com\"}";
Response response = RestAssured
.given()
.contentType(ContentType.JSON)
.body(payload)
.when()
.post("https://api.careerraah.com/v1/users");POST Request with Map Payload
Leverages REST-Assured's automatic object serialization to convert standard Java Map collections to JSON format utilizing active Jackson or Gson dependencies.
Map<String, Object> payload = new HashMap<>();
payload.put("username", "dev_tester");
payload.put("active", true);
Response response = RestAssured
.given()
.contentType(ContentType.JSON)
.body(payload)
.when()
.post("https://api.careerraah.com/v1/register");Pro-Tip: Using Maps is a fast way to generate payloads without creating dedicated class files.
PUT Request with JSON Update
Replaces or updates the target resource entirely with the provided payload representation.
Response response = RestAssured
.given()
.contentType(ContentType.JSON)
.body(updatedPayloadObject)
.when()
.put("/v1/users/1024");PATCH Request for Partial Updates
Performs a partial modification to an existing resource (e.g., toggling an operational status flag).
Response response = RestAssured
.given()
.contentType(ContentType.JSON)
.body("{\"status\":\"suspended\"}")
.when()
.patch("/v1/users/1024");DELETE Request
Sends an HTTP DELETE request to remove a specific resource from the server datastore.
Response response = RestAssured.delete("/v1/users/1024");GET with Custom Request Headers
Injects custom operational headers into the request context, commonly required for correlation logging or client identification.
Response response = RestAssured
.given()
.header("User-Agent", "AutomationEngine/1.0")
.header("X-Correlation-ID", "unique-uuid-123")
.when()
.get("/v1/health");Extract Status Code
Retrieves the standard HTTP response status code integer (e.g., 200, 201, 400, 404, 500).
int statusCode = response.getStatusCode();Extract Response Headers
Fetches metadata headers returned in the server response payload.
Headers headers = response.getHeaders();
String cacheControl = response.getHeader("Cache-Control");Extract Cookie Value
Extracts a specific cookie string value from the Set-Cookie response headers.
String sessionCookie = response.getCookie("JSESSIONID");Extract Raw Body String
Extracts the response payload as a raw, human-readable string. Great for debugging or logging.
String jsonResponse = response.getBody().asString();Extract Response Time
Returns the roundtrip server response time in milliseconds.
long responseTimeMs = response.getTime();Pro-Tip: Use this to verify Service Level Agreement (SLA) performances on your APIs.
Configure Base URI Globals
Sets global path prefixes to simplify endpoint parameters inside individual test scripts.
RestAssured.baseURI = "https://api.careerraah.com";
RestAssured.basePath = "/v1";Reset RestAssured Globals
Resets baseURI, basePath, filters, and parser configurations back to default settings.
RestAssured.reset();Log Request Details
Logs the complete request envelope (method, URI, headers, parameters, and body) directly to standard output.
Response response = RestAssured
.given()
.log().all()
.when()
.get("/v1/users");Log Response Details
Prints only the server response body text to standard output.
Response response = RestAssured.get("/v1/users");
response.then().log().body();Conditional Logging (If Error)
Saves stdout bloat by printing logs only when assertions or status validations fail.
RestAssured
.given()
.log().ifValidationFails()
.when()
.get("/v1/secure-data")
.then()
.statusCode(200);Pro-Tip: Excellent standard for CI/CD builds to keep deployment pipeline log files small.
Multi-Part Form Data (File Upload)
Simulates multipart HTML form submission, frequently required for dynamic profile uploads.
File uploadFile = new File("src/test/resources/avatar.jpg");
Response response = RestAssured
.given()
.multiPart("file", uploadFile)
.multiPart("description", "User avatar")
.when()
.post("/v1/profile/upload");Preemptive Basic Authentication
Sends HTTP Basic authentication headers immediately with the initial request, avoiding roundtrip challenges.
Response response = RestAssured
.given()
.auth().preemptive().basic("admin", "secret123")
.when()
.get("/v1/admin/dashboard");Challenged Basic Authentication
Waits for the server to reply with a 401 Unauthorized challenge before delivering Basic credentials.
Response response = RestAssured
.given()
.auth().basic("username", "password")
.when()
.get("/v1/secure");OAuth 2.0 Bearer Token Authorization
Attaches a secure Bearer validation token inside the HTTP Authorization request header.
String token = "eyJhbGciOiJIUzI1NiIsIn...";
Response response = RestAssured
.given()
.auth().oauth2(token)
.when()
.get("/v1/transactions");OAuth 1.0 Authorization Flow
Applies cryptographic OAuth 1.0 signatures to authorization parameters.
Response response = RestAssured
.given()
.auth().oauth("consumerKey", "consumerSecret", "accessToken", "tokenSecret")
.when()
.get("/v1/legacy-feed");Bypass SSL Verification
Instructs REST-Assured to accept self-signed or untrusted SSL certificates on local development environments.
Response response = RestAssured
.given()
.relaxedHTTPSValidation()
.when()
.get("https://self-signed.example.com/api");Pro-Tip: โ ๏ธ Do not use relaxedHTTPSValidation() in production suites! Keep it strictly inside QA/local test configurations.
Specify Custom SSL Keystore
Integrates client-side SSL certificates to authorize secure peer-to-peer microservices.
Response response = RestAssured
.given()
.keyStore("src/test/resources/mykeystore.jks", "keystorePassword")
.when()
.get("/secure");Set Connection Timeout
Limits network connection waits and socket read timeouts to prevent pipelines hanging on dead nodes.
RestAssuredConfig config = RestAssured.config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam("http.connection.timeout", 5000)
.setParam("http.socket.timeout", 5000));
Response response = RestAssured.given().config(config).get("/slow-endpoint");Reuse Cookie Configuration
Applies individual cookie settings with configured domain boundaries directly onto the request.
Cookie cookie = new Cookie.Builder("session", "active-uuid-998").setDomain("api.com").build();
Response response = RestAssured
.given()
.cookie(cookie)
.when()
.get("/v1/profile");Deliver Multiple Cookies
Incorporates multiple session cookies using key-value string arguments.
Response response = RestAssured
.given()
.cookies("theme", "dark", "view", "grid")
.when()
.get("/v1/settings");Redirect Handling (Disable Redirects)
Prevents automatic HTTP redirects (e.g., 301, 302 codes) from being processed, returning the source redirection headers instead.
Response response = RestAssured
.given()
.redirects().follow(false)
.when()
.get("/v1/redirect-source");Redirect Handling (Set Max Redirects)
Prevents infinite redirect loops by limiting maximum redirect hops to 3.
Response response = RestAssured
.given()
.redirects().max(3)
.when()
.get("/v1/redirect-loop");Deliver Query Parameters Map
Saves chaining calls by injecting all query variables from a Java Map collection.
Map<String, String> queryParams = new HashMap<>();
queryParams.put("page", "2");
queryParams.put("limit", "50");
Response response = RestAssured.given().queryParams(queryParams).get("/v1/logs");Specify ContentType Headers
Configures explicit server content negotiation headers for custom REST payloads.
Response response = RestAssured
.given()
.contentType("application/vnd.api+json")
.when()
.get("/v1/custom-resources");Extract Response to POJO
Deserializes the server JSON/XML response payload into a structured Java Plain Old Java Object (POJO).
UserResponse user = response.as(UserResponse.class);Pro-Tip: Define standard Lombok getter/setter models to easily map complex JSON responses.
Gzip Encoding Support
Declares client support for compression formats, decreasing payload transfers on large datasets.
Response response = RestAssured
.given()
.header("Accept-Encoding", "gzip, deflate")
.when()
.get("/v1/large-dataset");REST-Assured Custom Request Filter
Injects custom functional interceptors or execution hooks to record metrics or insert dynamic headers on every transaction.
Response response = RestAssured
.given()
.filter((requestSpec, responseSpec, ctx) -> {
System.out.println("Request URI: " + requestSpec.getURI());
return ctx.next(requestSpec, responseSpec);
})
.when()
.get("/health");Request Specification Builder
Encapsulates common request components into a reusable template, simplifying test scripting boilerplate.
RequestSpecification spec = new RequestSpecBuilder()
.setBaseUri("https://api.careerraah.com")
.setContentType(ContentType.JSON)
.addHeader("Auth", "Secret")
.build();Pro-Tip: Initialize your RequestSpecification in @BeforeSuite configs to enforce global project headers.
Response Specification Builder
Encapsulates standard assertion expectations, reducing redundant validation code across scripts.
ResponseSpecification resSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectHeader("Server", "Cloudflare")
.build();Apply Specifications Together
Executes an endpoint call combining both request and response templates simultaneously.
RestAssured
.given()
.spec(requestSpec)
.when()
.get("/v1/users")
.then()
.spec(responseSpec);Multi-Part Form Data (Byte Array)
Transfers raw file byte arrays in multipart requests without relying on local system pathing.
byte[] fileBytes = Files.readAllBytes(Paths.get("invoice.pdf"));
RestAssured
.given()
.multiPart("document", "invoice.pdf", fileBytes)
.when()
.post("/v1/invoices");Configure Connection Pooling Settings
Releases idle sockets immediately after validations finish, preserving active descriptors.
RestAssured.config = RestAssured.config()
.connectionConfig(ConnectionConfig.connectionConfig()
.closeIdleConnectionsAfterEachResponse());Request URI Encoding Override
Disables standard URL encoding to deliver custom, pre-escaped parameter formats.
Response response = RestAssured
.given()
.urlEncodingEnabled(false)
.when()
.get("/v1/search?query=val%2Bparam");Proxy Server Routing
Routes client requests through a corporate network proxy or debugging server (like Charles or Fiddler).
Response response = RestAssured
.given()
.proxy("proxy.mycompany.local", 8080)
.when()
.get("/v1/endpoints");Proxy Server Auth Credentials
Integrates authentication credentials while routing requests through secure corporate proxies.
Response response = RestAssured
.given()
.proxy(ProxySpecification.host("proxy.com").withPort(8080).withAuth("user", "pass"))
.when()
.get("/v1/data");Form Parameters POST Payload
Sends application/x-www-form-urlencoded POST payloads, typically required by standard OAuth token exchanges.
Response response = RestAssured
.given()
.formParam("username", "jane")
.formParam("grant_type", "password")
.when()
.post("/oauth/token");Validate Status Code Inline
Inlines validation logic to verify that the response status code is exactly 200.
RestAssured.get("/v1/users")
.then()
.statusCode(200);Assert JSON Body Key (EqualTo)
Uses Hamcrest Matchers to assert a specific root JSON field matches the expected value.
RestAssured.get("/v1/users/1024")
.then()
.body("name", Matchers.equalTo("Jane"));Assert JSON Array Length
Asserts that the root JSON array contains more than 5 child entries.
RestAssured.get("/v1/users")
.then()
.body("size()", Matchers.greaterThan(5));Assert Value inside Nested Object
Uses standard dot notation paths to navigate and validate values inside nested JSON structures.
RestAssured.get("/v1/users/1024")
.then()
.body("address.city", Matchers.equalTo("Chicago"));Assert List Elements Contain Value
Asserts that the response array or list field contains at least one match for the specified value.
RestAssured.get("/v1/users")
.then()
.body("roles", Matchers.hasItem("Admin"));JSON Schema Validation
Ensures the response payload fully matches the structured JSON schema file inside the test classpath.
RestAssured.get("/v1/users/1024")
.then()
.body(JsonSchemaValidator.matchesJsonSchemaInClasspath("user-schema.json"));Pro-Tip: Include the json-schema-validator module dependency inside your pom.xml file to enable this feature.
JSON Schema from File Path
Performs JSON schema validation loading the configuration parameters directly from a local File path.
File schema = new File("schemas/error-schema.json");
RestAssured.get("/v1/invalid")
.then()
.body(JsonSchemaValidator.matchesJsonSchema(schema));JsonPath Extract Field
Extracts an individual field value from the response body utilizing dot-path notations.
JsonPath jp = response.jsonPath();
String userMail = jp.getString("email");JsonPath Extract List Elements
Extracts all matches of a property inside a list structure into a flat Java List collection.
JsonPath jp = response.jsonPath();
List<String> cities = jp.getList("users.address.city");Groovy Find Method (JsonPath)
Uses dynamic Groovy inline expressions to search an array and return the first entry matching conditions.
JsonPath jp = response.jsonPath();
Map<String, Object> adminUser = jp.get("users.find { it.role == 'Admin' }");Pro-Tip: Extremely powerful for searching a dynamic database of items without writing manual java loop iterations!
Groovy FindAll Method (JsonPath)
Filters all users matching active conditions, returning a flat list of their associated email addresses.
JsonPath jp = response.jsonPath();
List<String> activeMails = jp.get("users.findAll { it.active == true }.email");Groovy Max Method (JsonPath)
Evaluates list models, filtering and returning the student object containing the highest score value.
int maxScore = response.jsonPath().getInt("students.max { it.score }.score");Assert ContentType Inline
Asserts that the server response header 'Content-Type' matches application/json.
RestAssured.get("/v1/health")
.then()
.contentType(ContentType.JSON);Assert Header Values
Verifies the presence and exact value of specific server security and encoding headers.
RestAssured.get("/v1/users")
.then()
.header("X-Frame-Options", "DENY")
.header("Content-Encoding", "gzip");Assert Response Time (SLA)
Asserts that the request roundtrip was completed within 800 milliseconds.
RestAssured.get("/v1/fast-api")
.then()
.time(Matchers.lessThan(800L));XMLPath Extract Value
Extracts data from standard XML responses utilizing clean path traversing logic.
XmlPath xp = response.xmlPath();
String text = xp.getString("bookstore.book[0].title");Assert XML Value (Matchers)
Directly validates dynamic XML response payload trees utilizing inlined Hamcrest assertions.
RestAssured.get("/v1/books.xml")
.then()
.body("bookstore.book[0].author", Matchers.equalTo("J.K. Rowling"));Extract XML Attribute
Extracts values from specific XML element attribute variables utilizing the @ prefix notation.
String isbn = response.xmlPath().getString("bookstore.book[0].@isbn");Assert Multiple Fields (Soft Asserts)
Validates multiple assertions within a single code execution, evaluating all rules even if one fails.
RestAssured.get("/v1/users/1024")
.then()
.body("name", Matchers.equalTo("Jane"),
"role", Matchers.equalTo("Editor"),
"age", Matchers.greaterThan(18));Validate XML Schema (XSD)
Validates XML response payloads against standard XSD schema definitions loaded from the classpath.
RestAssured.get("/v1/data.xml")
.then()
.body(RestAssuredMatchers.matchesXsdInClasspath("schema.xsd"));Playwright Request Context
Instantiates a new, standalone API request network container inside a Playwright test runner.
APIRequestContext request = playwright.request().newContext(new Playwright.CreateOptions()
.setBaseURL("https://api.careerraah.com"));Playwright GET Request
Executes a standalone HTTP GET request using Playwright's native network client API.
APIResponse response = request.get("/v1/users");Playwright GET with Query Params
Appends clean query parameters to the Playwright API request structure.
APIResponse response = request.get("/v1/users", RequestOptions.create()
.setQueryParam("role", "admin")
.setQueryParam("limit", 10));Playwright POST Request Payload
Sends a POST request with automatically serialized Java Map bodies.
Map<String, Object> data = new HashMap<>();
data.put("name", "Alice");
APIResponse response = request.post("/v1/users", RequestOptions.create()
.setData(data));Playwright Custom Request Headers
Incorporate operational request headers onto individual network dispatches.
APIResponse response = request.get("/v1/secure", RequestOptions.create()
.setHeader("X-Auth-Token", "secret-auth-value"));Extract Playwright Status Code
Returns the response status code integer from Playwright's network response layer.
int code = response.status();Extract Playwright Status Text
Retrieves status description text strings (e.g., 'OK' or 'Created').
String statusText = response.statusText();Assert Playwright Response Success
Convenient Boolean evaluator to confirm standard successful HTTP status code transactions.
boolean isOk = response.ok();
// Returns true if status code in the 200-299 rangeExtract JSON Payload (Playwright)
Parses the response body directly into a typed Google Gson JsonElement model.
JsonElement json = response.json();Extract Byte Array (Playwright)
Returns response body payloads as raw unparsed byte arrays, ideal for downloading static resources.
byte[] rawBodyBytes = response.body();Extract String Payload (Playwright)
Extracts response payloads as basic UTF-8 encoded text strings.
String responseString = response.text();Extract Response Headers (Playwright)
Fetches a full Map representation of all returned server headers.
Map<String, String> headers = response.headers();Close Request Context (Playwright)
Tears down the network context container, closing idle sockets and clearing associated session memory structures.
request.dispose();Pro-Tip: Always call dispose() in @AfterMethod annotations to prevent resource leaks during large-scale suites.
Configure Global Headers Context
Establishes standard default headers that apply automatically to every network execution inside this context.
APIRequestContext request = playwright.request().newContext(new Playwright.CreateOptions()
.setHeader("Authorization", "Bearer token")
.setHeader("Accept", "application/json"));Disable SSL Verification (Playwright)
Forces Playwright to bypass SSL validation checks when automating local development environments.
APIRequestContext request = playwright.request().newContext(new Playwright.CreateOptions()
.setIgnoreHTTPSErrors(true));Deliver Form UrlEncoded Body (Playwright)
Submits urlencoded request payloads using key-value pair parameters.
APIResponse response = request.post("/login", RequestOptions.create()
.setFormParam("user", "jane")
.setFormParam("pass", "1234"));Multipart File Upload (Playwright)
Executes standard file uploads utilizing Playwright's native FormData objects.
APIResponse response = request.post("/upload", RequestOptions.create()
.setMultipart(new FormData()
.set("file", Paths.get("test.png"))
.set("name", "Avatar")));Bypass Auto-Failures (FailOnStatusCode)
Prevents Playwright from automatically throwing exceptions on non-success HTTP codes, allowing explicit checks instead.
APIResponse response = request.get("/secure", RequestOptions.create()
.setFailOnStatusCode(false));Extract Playwright Cookie State
Captures complete session states (cookies and LocalStorage) to bypass login requirements on UI tests.
String state = browserContext.storageState();Pro-Tip: Use API calls to authenticate and fetch StorageStates, saving minutes of UI loading on every test run.
Inject Storage State to API Context
Launches a new API request context pre-populated with captured authentication tokens and cookies.
APIRequestContext request = playwright.request().newContext(new Playwright.CreateOptions()
.setStorageState(state));Establish JDBC Connection
Initializes a database connection pool to execute backend integrity verifications.
String url = "jdbc:postgresql://localhost:5432/qadb";
Connection conn = DriverManager.getConnection(url, "qa_user", "securePass");Execute Select SQL Query
Sends standard SQL queries and returns a ResultSet wrapper to navigate matched datasets.
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT email, role FROM users WHERE id=1024");Extract Query Data (String)
Iterates database pointers and retrieves data string values using named table columns.
if (rs.next()) {
String email = rs.getString("email");
String role = rs.getString("role");
}Execute Parameterized Prepared Query
Uses Prepared Statements to route parameters safely, avoiding SQL injection vulnerabilities.
String query = "SELECT * FROM users WHERE status = ? AND age > ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, "active");
ps.setInt(2, 18);
ResultSet rs = ps.executeQuery();Pro-Tip: Always use PreparedStatement for database interactions to ensure characters like single quotes are properly escaped.
Execute Database Update (DML)
Executes SQL modification commands (INSERT, UPDATE, DELETE), returning the row mutation counts.
Statement statement = conn.createStatement();
int rowsAffected = statement.executeUpdate("UPDATE users SET active = false WHERE id = 1024");Database Transaction Rollback Setup
Disables autocommit to run modifications, rolling back changes at the end of the test execution to preserve clean states.
conn.setAutoCommit(false);
// ... Execute database operations
conn.rollback();Pro-Tip: Crucial framework strategy! Prevents automation scripts from corrupting static shared testing databases.
Database Transaction Commit
Attempts database commits, catching failures and safely rolling back transaction states.
try {
// ... Database operations
conn.commit();
} catch (SQLException e) {
conn.rollback();
}Close Database Resource Pool
Releases database resources back to the server pools, preventing memory and socket descriptor leaks.
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();JDBC Connection with Properties
Launches database connections routes routing parameters using properties config files.
Properties props = new Properties();
props.setProperty("user", "qa_admin");
props.setProperty("password", "secret");
props.setProperty("ssl", "true");
Connection conn = DriverManager.getConnection("jdbc:postgresql://db.host.com/qadb", props);Verify Row Count (Select Count)
Performs counts on records to verify UI datasets match database outputs.
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS total FROM users");
if (rs.next()) {
int count = rs.getInt("total");
}Map ResultSet to Java Object List
Iterates through rows, creating collections of Java models to evaluate complex data scenarios.
List<User> users = new ArrayList<>();
while (rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("username")));
}Execute SQL Batch Mutations
Dispatches database updates in single batches, decreasing network latency.
Statement stmt = conn.createStatement();
stmt.addBatch("INSERT INTO logs VALUES(1, 'Access')");
stmt.addBatch("INSERT INTO logs VALUES(2, 'Modify')");
int[] results = stmt.executeBatch();Extract Database Schema Metadata
Fetches table schemas, column data types, and primary key relationships.
DatabaseMetaData meta = conn.getMetaData();
ResultSet tables = meta.getTables(null, null, "users", null);Database Transaction Savepoint Hook
Defines a transactional checkpoint (Savepoint) inside the active JDBC connection, enabling rollbacks to targeted checkpoints rather than reversing the whole transaction block.
Savepoint savepoint = conn.setSavepoint("Savepoint1");
// ... operations
conn.rollback(savepoint);Establish JDBC Connection Pool (HikariCP)
Initializes a high-performance database connection pool utilizing HikariCP to reuse active connections across parallel execution threads efficiently.
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/qadb");
config.setUsername("qa_user");
HikariDataSource ds = new HikariDataSource(config);
Connection conn = ds.getConnection();Fetch Column Metadata
Retrieves table column count and column property metadata directly from database result sets.
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
String columnName = rsmd.getColumnName(1);Call Stored Procedure
Prepares and executes a database stored procedure with defined input and output parameters.
CallableStatement cs = conn.prepareCall("{call get_user_by_id(?, ?)}");
cs.setInt(1, 1024);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
String name = cs.getString(2);Initialize WireMock Mock Server
Launches a local mock API server to simulate sandbox HTTP responses.
WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(8089));
wireMockServer.start();Stub GET Request (WireMock)
Creates stub definitions to intercept client requests, returning custom mock payloads.
wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/v1/mock-user"))
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"status\":\"MockedJane\"}")));Pro-Tip: Crucial for frontend testing when live backend APIs are down or unstable!
Stub GET Request with Delay (Latency Mocking)
Simulates network latency and endpoint timeout conditions in test suites.
wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/slow-endpoint"))
.willReturn(WireMock.aResponse()
.withStatus(200)
.withFixedDelay(3000))); // Simulates 3s delayStub GET Request with Header Matches
Stubs endpoints which execute response mapping only when specific header conditions are satisfied.
wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/secure"))
.withHeader("Authorization", WireMock.matching("Bearer .*"))
.willReturn(WireMock.ok()));Shut Down Mock Server
Stops WireMock server runtimes and releases occupied ports back to the system.
wireMockServer.stop();Parse JSON String (JSONObject)
Parses raw response strings into queryable JSON objects utilizing standard org.json library classes.
JSONObject json = new JSONObject(responseString);
String name = json.getString("name");
boolean active = json.getBoolean("active");Build JSON Payload (JSONObject)
Generates custom serialized JSON payloads programmatically.
JSONObject payload = new JSONObject();
payload.put("name", "Jane");
payload.put("roles", new JSONArray().put("User").put("Editor"));
String body = payload.toString();Validate JSON Array Iterations
Loops through JSON array elements to check specific fields individually.
JSONArray arr = new JSONArray(responseString);
for (int i = 0; i < arr.length(); i++) {
JSONObject item = arr.getJSONObject(i);
System.out.println(item.getString("id"));
}Jackson ObjectMapper Serialization
Converts standard Java objects to JSON formatted strings programmatically utilizing Jackson libraries.
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(new User("Jane", 28));Playwright API Tracing Capture
Triggers and captures advanced Playwright action traces, screenshots, and response snapshots to record full network executions for debugging.
browserContext.tracing().start(new Tracing.StartOptions()
.setScreenshots(true).setSnapshots(true));
// ... run API/UI steps
browserContext.tracing().stop(new Tracing.StopOptions()
.setPath(Paths.get("trace.zip")));WireMock Stateful Scenario Emulation
Sets up stateful stubs in WireMock to return different response values based on the dynamic scenario execution state.
wireMockServer.stubFor(WireMock.get(WireMock.urlEqualTo("/todo"))
.inScenario("TodoScenario")
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(WireMock.aResponse().withBody("Initial list"))
.willSetStateTo("ItemsAdded"));Load Application XML Config Parser
Parses structured XML files to dynamically resolve project automation properties.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("config.xml"));Gson Deserialization Utility
Parses JSON string parameters into typed Java objects leveraging Google's Gson library.
Gson gson = new Gson();
UserResponse user = gson.fromJson(jsonString, UserResponse.class);Load YAML Configuration Files
Parses advanced YAML files to extract hierarchical environment variables.
Yaml yaml = new Yaml();
Map<String, Object> data = yaml.load(new FileInputStream("config.yaml"));Verify API Performance Response Speed
Ensures roundtrip API latency measurements do not exceed standard Service Level Agreement performance boundaries.
RestAssured.get("/status")
.then()
.time(Matchers.lessThanOrEqualTo(1200L), TimeUnit.MILLISECONDS);Check REST-Assured Multipart Type Specification
Attaches a specific MIME-type multi-part document structure directly inside the request envelope.
RestAssured
.given()
.multiPart(new MultiPartSpecBuilder(file)
.controlName("attachment")
.mimeType("application/pdf").build())
.when()
.post("/upload");Verify Playwright Session Cookies
Retrieves the active browser authentication and tracking cookies from Playwright's network context.
List<Cookie> cookies = browserContext.cookies();
Assert.assertFalse(cookies.isEmpty());JDBC Connection Timeout Assertion
Defines the connection time limit in seconds to prevent database connection failures from hanging pipeline executions.
DriverManager.setLoginTimeout(5);
Connection conn = DriverManager.getConnection(url, user, password);