ποΈ Clean Architecture, Modularity & Zero HTTP Protocol Leakage
In enterprise software testing, writing monolithic test scripts where raw HTTP endpoints, query strings, serialization logic, transport headers, and verification assertions are coupled inside a single @Test method creates brittle, unmaintainable test automation. When a backend route changes or authentication headers rotate, hundreds of repetitive tests break simultaneously. Layered Framework Architecture adapts Uncle Bob's Clean Architecture and Domain-Driven Design (DDD) to automated API testing. By organizing test repositories into distinct, decoupled tiersβTransport/Client Layer (Service Clients encapsulating REST Assured DSL), Data/Model Layer (POJOs, DTOs, Lombok Builders), Infrastructure/Config Layer (Specification Factories, ThreadLocal managers), and the Business Test Layer (pure declarative TestNG scripts)βautomation engineers completely eliminate HTTP wire boilerplate from test cases, unlocking high reusability, seamless parallel concurrency, and maintainable regression suites.
ENTERPRISE LAYERED API AUTOMATION FRAMEWORK ARCHITECTURE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TIER 1: BUSINESS TEST & SCENARIO LAYER (src/test/java/com/nikita/tests) β
β β’ Extends BaseTest β
β β’ Pure business workflows (Zero given().when().then() HTTP transport leakage!) β
β β’ Uses AssertJ fluent assertions: assertThat(student.getFullName()).isEqualTo("Nikita"); β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Invokes domain actions via Service Clients)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TIER 2: SERVICE CLIENT / CONTROLLER LAYER (src/test/java/com/nikita/clients) β
β β’ StudentServiceClient.java | CurriculumServiceClient.java | AuthServiceClient.java β
β β’ Encapsulates HTTP Verbs, Path Parameters, Route Resolution, and Deserialization β
β β’ Exposes high-level Java methods: registerStudent(DTO), getStudentById(id), purgeStudent(id)β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β TIER 3: DATA & MODEL LAYER (DTOs) β β TIER 4: INFRASTRUCTURE & SPEC FACTORY β
ββββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β β’ Strong typing via POJOs & Lombok @Builder β β β’ RequestSpecFactory.java β
β β’ Jackson Annotations (@JsonProperty, @Json..) β β β’ ResponseSpecFactory.java β
β β’ TestDataFactory.java (Dynamic Generators) β β β’ ThreadLocalContextManager (Concurrency) β
β β’ External JSON/CSV Ingestion Loaders β β β’ Filter Interceptors (OAuth2, Allure, Logs) β
ββββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Executed over TLS Wire Socket)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TIER 5: CORE HTTP ENGINE LAYER (io.restassured.RestAssured & Apache HttpClient) β
β Transmits RFC 8259 JSON packets across socket boundaries to remote API microservices β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
rest-assured-enterprise-framework/
βββ pom.xml
βββ src/
βββ test/
βββ java/
β βββ com/nikita/restassured/
β βββ clients/ βββΊ TIER 2: Service Client Wrappers (Controllers)
β β βββ BaseServiceClient.java
β β βββ StudentServiceClient.java
β β βββ AuthServiceServiceClient.java
β βββ config/ βββΊ TIER 4: Environment & Spec Configuration
β β βββ EnvironmentConfig.java
β β βββ RequestSpecFactory.java
β β βββ ResponseSpecFactory.java
β βββ context/ βββΊ TIER 4: Thread-Safe State Management
β β βββ ThreadLocalContext.java
β βββ filters/ βββΊ TIER 4: Interceptors & Middleware
β β βββ CorrelationFilter.java
β β βββ OAuth2RenewalFilter.java
β βββ models/ βββΊ TIER 3: Strongly-Typed Domain POJOs / DTOs
β β βββ request/
β β β βββ StudentRegistrationRequest.java
β β βββ response/
β β βββ StudentProfileResponse.java
β β βββ ApiResponseEnvelope.java
β βββ factories/ βββΊ TIER 3: Dynamic Data Generators
β β βββ StudentDataFactory.java
β βββ tests/ βββΊ TIER 1: Declarative TestNG Test Suites
β βββ BaseTest.java
β βββ StudentRegistrationTest.java
β βββ StudentSecurityRbacTest.java
βββ resources/
βββ data/ βββΊ External CSV and Excel Test Matrices
β βββ students-dataset.csv
βββ payloads/ βββΊ JSON Template Fixtures
β βββ student-template.json
βββ schemas/ βββΊ Draft-07 JSON & W3C XSD Contracts
β βββ student-v1-schema.json
βββ testng-parallel.xml βββΊ Concurrency & Suite Runner Configurations
BaseServiceClient.java. Encapsulates underlying REST Assured HTTP primitives (GET, POST, PUT, DELETE), binds specifications, attaches filters, and returns raw Response wrappers.
package com.nikita.restassured.clients;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import static io.restassured.RestAssured.given;
public abstract class BaseServiceClient {
// Subclasses provide their service-specific RequestSpecification
protected abstract RequestSpecification getRequestSpec();
// -------------------------------------------------------------
// PROTECTED HTTP PRIMITIVE WRAPPERS (CENTRALIZED EXECUTION)
// -------------------------------------------------------------
protected Response executeGet(String endpointPath) {
return given()
.spec(getRequestSpec())
.when()
.get(endpointPath)
.then()
.extract().response();
}
protected Response executeGetWithParam(String endpointPath, String paramName, Object paramValue) {
return given()
.spec(getRequestSpec())
.pathParam(paramName, paramValue)
.when()
.get(endpointPath)
.then()
.extract().response();
}
protected Response executePost(String endpointPath, Object payload) {
return given()
.spec(getRequestSpec())
.body(payload)
.when()
.post(endpointPath)
.then()
.extract().response();
}
protected Response executeDelete(String endpointPath, String paramName, Object paramValue) {
return given()
.spec(getRequestSpec())
.pathParam(paramName, paramValue)
.when()
.delete(endpointPath)
.then()
.extract().response();
}
}
registerStudent, getStudentById, deleteStudent) that map directly to domain actions and return strongly-typed DTOs or responses.
package com.nikita.restassured.clients;
import com.nikita.restassured.config.RequestSpecFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import com.nikita.restassured.models.response.StudentProfileResponse;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class StudentServiceClient extends BaseServiceClient {
private static final String BASE_PATH = "/v1/students";
private static final String STUDENT_BY_ID_PATH = BASE_PATH + "/{studentId}";
@Override
protected RequestSpecification getRequestSpec() {
// Obtains pre-configured, thread-safe specification for student service
return RequestSpecFactory.getStudentMicroserviceSpec();
}
// -------------------------------------------------------------
// DOMAIN BUSINESS METHODS (ZERO REST ASSURED SYNTAX EXPOSED TO TESTS!)
// -------------------------------------------------------------
/**
* Registers a new student and returns the raw Response for status verification
*/
public Response registerStudentRaw(StudentRegistrationRequest request) {
return executePost(BASE_PATH, request);
}
/**
* Registers a new student and unmarshals directly into a typed StudentProfileResponse POJO
*/
public StudentProfileResponse registerStudent(StudentRegistrationRequest request) {
return executePost(BASE_PATH, request)
.then()
.statusCode(201)
.extract()
.as(StudentProfileResponse.class);
}
/**
* Retrieves student profile by unique ID and unmarshals into POJO
*/
public StudentProfileResponse getStudentById(String studentId) {
return executeGetWithParam(STUDENT_BY_ID_PATH, "studentId", studentId)
.then()
.statusCode(200)
.extract()
.as(StudentProfileResponse.class);
}
/**
* Deletes student by ID and returns raw Response for status checks (e.g. 204 vs 404)
*/
public Response deleteStudent(String studentId) {
return executeDelete(STUDENT_BY_ID_PATH, "studentId", studentId);
}
}
@Builder, @Getter, and Jackson's @Jacksonized to establish immutable, expressive request models and resilient response envelopes.
package com.nikita.restassured.models.request;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.jackson.Jacksonized;
@Getter
@Builder(toBuilder = true)
@Jacksonized
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class StudentRegistrationRequest {
@JsonProperty("studentId")
private String studentId;
@JsonProperty("fullName")
private String fullName;
@JsonProperty("email")
private String email;
@JsonProperty("academicTrack")
private String academicTrack;
@JsonProperty("enrolledCredits")
private int enrolledCredits;
}
// ==============================================================================
// RESPONSE MODEL (src/test/java/com/nikita/restassured/models/response/...)
// ==============================================================================
package com.nikita.restassured.models.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.ToString;
@Getter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class StudentProfileResponse {
@JsonProperty("id")
private String id;
@JsonProperty("fullName")
private String fullName;
@JsonProperty("email")
private String email;
@JsonProperty("academicTrack")
private String academicTrack;
@JsonProperty("enrolledCredits")
private int enrolledCredits;
@JsonProperty("status")
private String status;
// Default no-argument constructor for Jackson unmarshalling
public StudentProfileResponse() {}
}
package com.nikita.restassured.factories;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import java.util.Random;
import java.util.UUID;
public class StudentDataFactory {
private static final Random RANDOM = new Random();
/**
* Generates a fully populated, valid baseline StudentRegistrationRequest
*/
public static StudentRegistrationRequest createValidStudent() {
String randomSuffix = UUID.randomUUID().toString().substring(0, 6);
return StudentRegistrationRequest.builder()
.studentId("STU-" + (10000 + RANDOM.nextInt(90000)))
.fullName("Candidate_" + randomSuffix)
.email("student." + randomSuffix + "@nikita-infotech.com")
.academicTrack("ENTERPRISE_AUTOMATION")
.enrolledCredits(16)
.build();
}
/**
* Creates an edge-case student with minimum allowable credits
*/
public static StudentRegistrationRequest createMinCreditsStudent() {
return createValidStudent().toBuilder()
.enrolledCredits(1)
.build();
}
/**
* Creates an invalid student with negative credits for 422 boundary validation
*/
public static StudentRegistrationRequest createInvalidCreditsStudent() {
return createValidStudent().toBuilder()
.enrolledCredits(0)
.build();
}
}
BaseTest, calling StudentServiceClient, and asserting outcomes using AssertJβwith zero given().when().then() leakage.
package com.nikita.restassured.tests;
import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import com.nikita.restassured.models.response.StudentProfileResponse;
import io.restassured.response.Response;
import org.assertj.core.api.Assertions;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class StudentRegistrationTest extends BaseTest {
private StudentServiceClient studentClient;
@BeforeClass
public void setupClient() {
// Initialize service controller
studentClient = new StudentServiceClient();
}
@Test(description = "Verify successful registration of a valid student entity")
public void testStudentRegistrationSuccess() {
// Step 1: Arrange test data via factory
StudentRegistrationRequest requestPayload = StudentDataFactory.createValidStudent();
// Step 2: Act via domain Service Client (No given/when/then in test!)
StudentProfileResponse response = studentClient.registerStudent(requestPayload);
// Step 3: Assert via AssertJ fluent assertions
Assertions.assertThat(response)
.as("Student registration profile must be returned")
.isNotNull();
Assertions.assertThat(response.getId())
.as("Returned student ID must match generated ID")
.isEqualTo(requestPayload.getStudentId());
Assertions.assertThat(response.getFullName())
.as("Candidate full name check")
.isEqualTo(requestPayload.getFullName());
Assertions.assertThat(response.getStatus())
.as("Default registration status must be ACTIVE")
.isEqualTo("ACTIVE");
System.out.printf("[TEST PASS] Successfully registered: %s (%s)%n",
response.getFullName(), response.getId());
}
@Test(description = "Verify boundary validation rejects enrollment with 0 credits")
public void testRejectZeroCreditsEnrollment() {
StudentRegistrationRequest invalidPayload = StudentDataFactory.createInvalidCreditsStudent();
// Capture raw response to assert HTTP boundary rejection
Response response = studentClient.registerStudentRaw(invalidPayload);
Assertions.assertThat(response.getStatusCode())
.as("Must return 422 Unprocessable Entity for 0 credits")
.isEqualTo(422);
Assertions.assertThat(response.jsonPath().getString("detail"))
.as("Error detail check")
.contains("Credits must be between 1 and 30");
System.out.println("[TEST PASS] Boundary condition rejected 0 credits as expected.");
}
}
RequestSpecFactory. Assembles base URIs, JSON MIME negotiation, correlation tracing, and authentication schemes into immutable specifications consumed by service clients.
package com.nikita.restassured.config;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import java.util.UUID;
public class RequestSpecFactory {
private static final String TARGET_ENV = System.getProperty("env", "staging").toLowerCase();
private static String resolveBaseUrl() {
switch (TARGET_ENV) {
case "dev":
return "https://dev-api.nikita-infotech.com";
case "qa":
return "https://qa-api.nikita-infotech.com";
case "prod":
return "https://api.nikita-infotech.com";
case "staging":
default:
return "https://staging-api.nikita-infotech.com";
}
}
public static RequestSpecification getStudentMicroserviceSpec() {
return new RequestSpecBuilder()
.setBaseUri(resolveBaseUrl())
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.addHeader("X-Correlation-Id", "TRACE-" + UUID.randomUUID().toString().substring(0, 8))
.addHeader("X-Client-Platform", "Enterprise-Masterclass-Runner")
.log(LogDetail.URI) // Logs target URI automatically
.build();
}
}
package com.nikita.restassured.triage;
import org.testng.annotations.Test;
public class ArchitectureSmellsTriageTest {
// ==========================================================================
// ANTI-PATTERN 1: HTTP PROTOCOL LEAKAGE INSIDE TEST METHODS
// SMELL: given().header("Auth", "..").when().post("/v1/students").then()...
// PROBLEM: Test code is coupled directly to endpoints, verbs, and auth headers.
// REFACTOR: Delegate execution to StudentServiceClient.registerStudent(DTO).
// ==========================================================================
// ==========================================================================
// ANTI-PATTERN 2: EMBEDDING TEST ASSERTIONS INSIDE SERVICE CLIENTS
// SMELL: public void getStudent(String id) { get(...).then().statusCode(200); }
// PROBLEM: Prevents testing negative scenarios! What if a test expects 404?
// REFACTOR: Return DTOs on success or raw Response so tests can assert status!
// ==========================================================================
// ==========================================================================
// ANTI-PATTERN 3: HARDCODING RAW STRINGS IN PLACE OF DTOs
// SMELL: String json = "{\"fullName\": \"" + name + "\"}";
// PROBLEM: Brittle string escaping, syntax typos, and zero refactor safety.
// REFACTOR: Use Lombok-annotated POJOs with Jackson serialization.
// ==========================================================================
@Test(description = "Verify refactored architecture adheres to Clean Separation of Concerns")
public void testCleanArchitectureAdherence() {
System.out.println("[β] Architecture Audit: Zero HTTP wire primitives found in test scripts.");
System.out.println("[β] Architecture Audit: Endpoints, paths, and headers encapsulated in clients.");
System.out.println("[β] Architecture Audit: DTO models enforce strict type safety across all layers.");
}
}
LAYERED FRAMEWORK ARCHITECTURE SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β FRAMEWORK LAYER β PRIMARY CLASS ARTIFACTS β KEY DEPENDENCIES β PRIMARY ARCHITECTURAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Tier 1: Business Tests β *Test.java (extends BaseTest)β TestNG, AssertJ β Declarative workflow checks β
β Tier 2: Service Clients β *ServiceClient.java β BaseServiceClientβ Encapsulates HTTP endpoints β
β Tier 3: Data / Models β RequestDTO / ResponseDTO β Lombok, Jackson β Strongly-typed data models β
β Tier 3: Data Factories β *DataFactory.java β Java Faker, DTOs β Dynamic test data generation β
β Tier 4: Specifications β Request/ResponseSpecFactory β REST Assured β Centralized connection specs β
β Tier 4: State Context β ThreadLocalContextManager β ThreadLocal β Thread-safe concurrency store β
β Tier 4: Interceptors β Custom Filters (OAuth2, Log) β REST Assured Fltrβ Middleware wire interceptors β
β Tier 5: Transport Core β RestAssured, Apache HttpClnt β Socket / Wire β Low-level network I/O β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 LAYERED ARCHITECTURE BEST PRACTICES: β
β 1. Zero HTTP leakage in test methods: Tests should never call given().when().then() directly. β
β 2. Return typed DTOs and raw Responses: Allow tests to assert success POJOs or negative HTTP codes. β
β 3. Encapsulate endpoints in Service Clients: Centralize routes so URL updates touch only 1 class. β
β 4. Decouple data generation via Data Factories: Produce realistic random payloads in one line. β
β 5. Manage specifications via ThreadLocal factories: Guarantee 100% thread safety for parallel runs. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ