ποΈ End-to-End Data Verification, Asynchronous State & Database Integrity
Asserting an HTTP status code 200 OK or 201 Created with a valid JSON body is only half of thorough API testing. Often, an API gateway or backend service acknowledges receipt of a payload and echoes back expected attributes, but fails to commit the transaction, silently drops fields during Object-Relational Mapping (ORM), mutates audit timestamps, or leaves dirty state in asynchronous event pipelines. Database Validation via JDBC establishes definitive Two-Phase State Reconciliation. By orchestrating direct database checks in REST Assured automation suitesβleveraging HikariCP connection pooling, parameterized PreparedStatement executions, and AssertJ entity comparisonsβautomation engineers confirm that every HTTP POST, PUT, and DELETE cleanly mutates persistent database rows (MySQL, PostgreSQL, Oracle), validates transactional integrity, and executes automated data tear-down routines.
TWO-PHASE API & DATABASE STATE RECONCILIATION ARCHITECTURE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TEST RUNNER (TestNG + REST Assured Test Suite) β
β StudentRegistrationRequest payload = StudentDataFactory.createValidStudent(); β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ (PHASE 1: HTTP WIRE TRANSMISSION) βΌ (PHASE 2: DIRECT JDBC RECONCILIATION)
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP API GATEWAY / MICROSERVICE PIPELINE β β HIKARICP CONNECTION POOL (Pooled DataSource) β
ββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β 1. POST /v1/students β β 1. Rent Connection: ConnectionPool.getConn() β
β 2. Backend ORM saves to Database β β 2. SELECT * FROM students WHERE id = ? β
β 3. Server returns HTTP 201 Created β β 3. Extract ResultSet to StudentEntity model β
β 4. REST Assured asserts status & JSON body β β 4. Reconcile DB fields against Wire payload β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CROSS-TIER ASSERTION RECONCILIATION (AssertJ) β
β βββ assertThat(dbEntity.getFullName()).isEqualTo(apiResponse.getFullName()); β
β βββ assertThat(dbEntity.getEnrolledCredits()).isEqualTo(payload.getEnrolledCredits()); β
β βββ assertThat(dbEntity.getCreatedTimestamp()).isCloseTo(Instant.now(), within(5, SECONDS)); β
β βββ assertThat(dbEntity.getTenantRegion()).isEqualTo("MH-PUNE-WEST"); β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TEARDOWN / DATA PURGE PHASE (@AfterMethod) β
β DELETE FROM students WHERE student_id = ? (Ensures 100% zero-footprint test isolation) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
package com.nikita.restassured.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DatabaseManager {
private static final HikariDataSource dataSource;
static {
// Read database configuration from system flags or properties
String jdbcUrl = System.getProperty("db.url", "jdbc:mysql://localhost:3306/enterprise_masterclass?useSSL=false&serverTimezone=UTC");
String username = System.getProperty("db.user", "sdet_tester");
String password = System.getProperty("db.password", "TestPass#2026");
HikariConfig config = new HikariConfig();
config.setJdbcUrl(jdbcUrl);
config.setUsername(username);
config.setPassword(password);
config.setDriverClassName("com.mysql.cj.jdbc.Driver");
// Connection pool sizing and tuning
config.setMaximumPoolSize(15); // Max concurrent connections in pool
config.setMinimumIdle(5); // Minimum warm idle connections
config.setConnectionTimeout(10000); // 10s timeout to rent connection
config.setIdleTimeout(600000); // 10 minutes idle timeout
config.setMaxLifetime(1800000); // 30 minutes max connection lifetime
config.setPoolName("RestAssuredHikariPool");
dataSource = new HikariDataSource(config);
System.out.println("[*] HikariCP Connection Pool initialized successfully.");
}
/**
* Rents an active connection from the pool
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* Graceful teardown of pool during suite shutdown
*/
public static void shutdown() {
if (dataSource != null && !dataSource.isClosed()) {
dataSource.close();
System.out.println("[*] HikariCP Connection Pool closed.");
}
}
}
PreparedStatement queries, extracts records into typed entity objects, checks row existence, and executes parameterized test cleanup routines.
package com.nikita.restassured.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Optional;
public class StudentDao {
public static class StudentDbRecord {
public String studentId;
public String fullName;
public String email;
public String academicTrack;
public int enrolledCredits;
public String status;
public Timestamp createdAt;
}
/**
* Queries a student record by unique primary key
*/
public Optional<StudentDbRecord> getStudentById(String studentId) {
String sql = "SELECT student_id, full_name, email, academic_track, enrolled_credits, status, created_at " +
"FROM students WHERE student_id = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, studentId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
StudentDbRecord record = new StudentDbRecord();
record.studentId = rs.getString("student_id");
record.fullName = rs.getString("full_name");
record.email = rs.getString("email");
record.academicTrack = rs.getString("academic_track");
record.enrolledCredits = rs.getInt("enrolled_credits");
record.status = rs.getString("status");
record.createdAt = rs.getTimestamp("created_at");
return Optional.of(record);
}
}
} catch (SQLException e) {
throw new RuntimeException("Database query failed for studentId: " + studentId, e);
}
return Optional.empty();
}
/**
* Purges a student record created during testing (Teardown routine)
*/
public boolean deleteStudentById(String studentId) {
String sql = "DELETE FROM students WHERE student_id = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, studentId);
int rowsDeleted = stmt.executeUpdate();
return rowsDeleted > 0;
} catch (SQLException e) {
throw new RuntimeException("Database cleanup failed for studentId: " + studentId, e);
}
}
}
201 Created wire response, then queries the physical database to reconcile column values and timestamps.
package com.nikita.restassured.database;
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 org.assertj.core.api.Assertions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
public class TwoPhaseRegistrationVerificationTest {
private StudentServiceClient studentClient;
private StudentDao studentDao;
private String registeredStudentId;
@BeforeClass
public void setup() {
studentClient = new StudentServiceClient();
studentDao = new StudentDao();
}
@Test(description = "Two-Phase Verification: Verify HTTP 201 wire response matches physical database row")
public void testStudentRegistrationWithDatabaseReconciliation() {
// Arrange: Generate dynamic valid candidate payload
StudentRegistrationRequest payload = StudentDataFactory.createValidStudent();
registeredStudentId = payload.getStudentId();
// -------------------------------------------------------------
// PHASE 1: HTTP WIRE TRANSMISSION & RESPONSE VALIDATION
// -------------------------------------------------------------
StudentProfileResponse wireResponse = studentClient.registerStudent(payload);
Assertions.assertThat(wireResponse.getId())
.as("Wire response ID must match request ID")
.isEqualTo(payload.getStudentId());
Assertions.assertThat(wireResponse.getStatus())
.as("Wire response status check")
.isEqualTo("ACTIVE");
System.out.println("[Phase 1] HTTP Wire response validated: 201 Created for ID: " + registeredStudentId);
// -------------------------------------------------------------
// PHASE 2: DIRECT DATABASE QUERY & STATE RECONCILIATION
// -------------------------------------------------------------
Optional<StudentDao.StudentDbRecord> dbRecordOpt = studentDao.getStudentById(registeredStudentId);
Assertions.assertThat(dbRecordOpt)
.as("Physical database row must exist in 'students' table")
.isPresent();
StudentDao.StudentDbRecord dbRecord = dbRecordOpt.get();
// Reconcile physical DB columns against request payload & wire response:
Assertions.assertThat(dbRecord.fullName)
.as("DB column 'full_name' must match wire payload")
.isEqualTo(payload.getFullName());
Assertions.assertThat(dbRecord.email)
.as("DB column 'email' must match wire payload")
.isEqualTo(payload.getEmail());
Assertions.assertThat(dbRecord.enrolledCredits)
.as("DB column 'enrolled_credits' must match wire payload")
.isEqualTo(payload.getEnrolledCredits());
Assertions.assertThat(dbRecord.status)
.as("DB column 'status' must be ACTIVE")
.isEqualTo("ACTIVE");
// Verify audit timestamp was populated within the last 10 seconds:
Assertions.assertThat(dbRecord.createdAt.toInstant())
.as("DB column 'created_at' timestamp must reflect recent insertion")
.isCloseTo(Instant.now(), Assertions.within(10, ChronoUnit.SECONDS));
System.out.println("[Phase 2] Database row reconciled: All DB columns match wire payload accurately.");
}
@AfterMethod(alwaysRun = true)
public void teardownTestData() {
if (registeredStudentId != null) {
boolean deleted = studentDao.deleteStudentById(registeredStudentId);
System.out.println("[Teardown] Purged student record from database: " + registeredStudentId + " (Success: " + deleted + ")");
}
}
}
204 No Content status code, and queries the database via JDBC to confirm that the physical row was purged.
package com.nikita.restassured.database;
import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import io.restassured.response.Response;
import org.assertj.core.api.Assertions;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.Optional;
public class DeleteVerificationWithDatabaseTest {
private StudentServiceClient studentClient;
private StudentDao studentDao;
@BeforeClass
public void setup() {
studentClient = new StudentServiceClient();
studentDao = new StudentDao();
}
@Test(description = "Verify HTTP DELETE returns 204 and physically purges row from database")
public void testDeleteStudentDatabaseVerification() {
// Step 1: Pre-condition - Register a student to delete
StudentRegistrationRequest student = StudentDataFactory.createValidStudent();
studentClient.registerStudent(student);
String targetId = student.getStudentId();
// Confirm row is present in DB prior to deletion
Assertions.assertThat(studentDao.getStudentById(targetId)).isPresent();
System.out.println("[*] Pre-condition confirmed: Student row exists in DB: " + targetId);
// Step 2: Act - Execute HTTP DELETE via Service Client
Response deleteResponse = studentClient.deleteStudent(targetId);
// Assert HTTP status code is 204 No Content
Assertions.assertThat(deleteResponse.getStatusCode())
.as("DELETE endpoint must return HTTP 204 No Content")
.isEqualTo(204);
System.out.println("[*] DELETE /v1/students/" + targetId + " returned HTTP 204 No Content.");
// Step 3: Assert - Verify physical database state
Optional<StudentDao.StudentDbRecord> recordAfterDelete = studentDao.getStudentById(targetId);
Assertions.assertThat(recordAfterDelete)
.as("Student row must be completely removed from database after HTTP DELETE")
.isEmpty();
System.out.println("[β] Database verified: Record " + targetId + " successfully purged from database table.");
}
}
package com.nikita.restassured.database;
import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import org.assertj.core.api.Assertions;
import org.awaitility.Awaitility;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
public class AsyncDatabaseValidationTest {
private final StudentServiceClient studentClient = new StudentServiceClient();
private final StudentDao studentDao = new StudentDao();
private String asyncStudentId;
@Test(description = "Verify asynchronous event-driven database persistence using Awaitility polling")
public void testAsyncEventPersistence() {
StudentRegistrationRequest payload = StudentDataFactory.createValidStudent();
asyncStudentId = payload.getStudentId();
// Dispatch async registration request (HTTP 202 Accepted)
studentClient.registerStudentRaw(payload)
.then()
.statusCode(201);
System.out.println("[*] Dispatched registration. Polling database for asynchronous consumer write...");
AtomicReference<StudentDao.StudentDbRecord> recordRef = new AtomicReference<>();
// Poll database every 500ms for up to 5 seconds until the background worker writes the row
Awaitility.await()
.atMost(Duration.ofSeconds(5))
.pollInterval(Duration.ofMillis(500))
.alias("Wait for Kafka consumer to persist student record to database")
.untilAsserted(() -> {
Optional<StudentDao.StudentDbRecord> record = studentDao.getStudentById(asyncStudentId);
Assertions.assertThat(record).isPresent();
recordRef.set(record.get());
});
StudentDao.StudentDbRecord persistedRecord = recordRef.get();
Assertions.assertThat(persistedRecord.status).isEqualTo("ACTIVE");
Assertions.assertThat(persistedRecord.fullName).isEqualTo(payload.getFullName());
System.out.println("[β] Asynchronous persistence confirmed: Record found in database within SLA window.");
}
@AfterMethod(alwaysRun = true)
public void cleanUp() {
if (asyncStudentId != null) {
studentDao.deleteStudentById(asyncStudentId);
}
}
}
tenant_id) are saved correctly and rows remain hidden from other tenants.
package com.nikita.restassured.database;
import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import org.assertj.core.api.Assertions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MultiTenantDatabaseIsolationTest {
private final StudentServiceClient studentClient = new StudentServiceClient();
private final StudentDao studentDao = new StudentDao();
private String testStudentId;
@Test(description = "Verify student record is persisted with strict tenant partitioning in database")
public void testTenantPartitioningInDatabase() throws SQLException {
StudentRegistrationRequest student = StudentDataFactory.createValidStudent();
testStudentId = student.getStudentId();
// Register student under Pune tenant
studentClient.registerStudent(student);
// Direct SQL checking tenant association
String sql = "SELECT tenant_id FROM students WHERE student_id = ?";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, testStudentId);
try (ResultSet rs = stmt.executeQuery()) {
Assertions.assertThat(rs.next())
.as("Record must exist in database")
.isTrue();
String assignedTenant = rs.getString("tenant_id");
System.out.println("[*] Queried tenant_id from database: " + assignedTenant);
Assertions.assertThat(assignedTenant)
.as("Tenant ID must be partitioned to Pune region")
.isEqualTo("MH-PUNE-WEST");
}
}
System.out.println("[β] Multi-tenant isolation verified: Row is correctly tagged with tenant identifier.");
}
@AfterMethod(alwaysRun = true)
public void cleanUp() {
if (testStudentId != null) {
studentDao.deleteStudentById(testStudentId);
}
}
}
package com.nikita.restassured.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
public class DatabaseSeedingHelper {
/**
* Directly inserts a prerequisite student record into the database for testing GET/PUT operations
*/
public static void seedStudent(String studentId, String fullName, String email, String track, int credits) {
String sql = "INSERT INTO students (student_id, full_name, email, academic_track, enrolled_credits, status, tenant_id, created_at) " +
"VALUES (?, ?, ?, ?, ?, 'ACTIVE', 'MH-PUNE-WEST', ?) " +
"ON DUPLICATE KEY UPDATE full_name = VALUES(full_name), status = 'ACTIVE'";
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, studentId);
stmt.setString(2, fullName);
stmt.setString(3, email);
stmt.setString(4, track);
stmt.setInt(5, credits);
stmt.setTimestamp(6, Timestamp.from(Instant.now()));
int rows = stmt.executeUpdate();
System.out.printf("[DB SEED] Seeded student record '%s' directly into DB (Rows affected: %d)%n",
studentId, rows);
} catch (SQLException e) {
throw new RuntimeException("Failed to seed student record: " + studentId, e);
}
}
}
ConnectionPoolTimeoutException, preventing unclosed statements, tuning query timeouts, and resolving transaction isolation deadlocks in parallel test suites.
package com.nikita.restassured.database;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseTriageTest {
// ==========================================================================
// PITFALL 1: CONNECTION POOL EXHAUSTION DUE TO UNCLOSED STATEMENTS / CONNS
// SYMPTOM: com.zaxxer.hikari.pool.HikariPool$PoolBag: Connection timeout
//
// CAUSE: Code opens a Connection without closing it, holding it open indefinitely.
// Under parallel TestNG runs, all 15 connections are locked, starving worker threads!
//
// FIX: Always enclose Connection, PreparedStatement, and ResultSet inside
// a try-with-resources statement!
// ==========================================================================
@Test(description = "Verify safe query execution with statement timeout and zero connection leakage")
public void testSafeQueryWithTimeout() {
String sql = "SELECT 1";
// All 3 JDBC objects declared inside try-with-resources guarantees automatic closure:
try (Connection conn = DatabaseManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
// Enforce explicit statement timeout (e.g. 3 seconds) to prevent hanging tests:
stmt.setQueryTimeout(3);
try (ResultSet rs = stmt.executeQuery()) {
Assert.assertTrue(rs.next());
Assert.assertEquals(rs.getInt(1), 1);
}
System.out.println("[β] Executed query safely with auto-closure and explicit 3s statement timeout.");
} catch (SQLException e) {
Assert.fail("Database query execution failed: " + e.getMessage());
}
}
}
DATABASE VALIDATION SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β VALIDATION CONSTRUCT β JDBC / UTILITY MECHANISM β LIFECYCLE TIER β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β HikariCP Pool β HikariDataSource β Global Singleton β High-speed connection reuse β
β Parameterized Query β PreparedStatement (?) β DAO Layer β Prevents SQL injection bugs β
β Try-With-Resources β try (Connection, Stmt, RS) β Execution Block β Guarantees zero socket leaks β
β Statement Timeout β stmt.setQueryTimeout(3) β Query Level β Fails fast on locked rows β
β Two-Phase Validation β REST Assured + JDBC DAO β Test Method β Wire response vs. DB state β
β Eventual Consistency β Awaitility.await().until(..) β Async Testing β Polls DB for async queue writeβ
β Data Seeding β DatabaseSeedingHelper β Pre-Condition β Sets up prerequisites via SQL β
β Automated Teardown β DAO.deleteById(studentId) β @AfterMethod β Zero-footprint test isolation β
β Tenant Isolation Audit β SELECT tenant_id WHERE id=? β Security Audit β Verifies multi-tenant bounds β
β AssertJ Reconciliation β assertThat(db).isEqualTo(reqβ Assertion Phase β Strong entity reconciliation β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 DATABASE VALIDATION BEST PRACTICES: β
β 1. Always use connection pooling: Use HikariCP to prevent socket exhaustion during parallel runs. β
β 2. Enclose all JDBC calls in try-with-resources: Prevent connection leaks in long-running CI runners. β
β 3. Always clean up test data in @AfterMethod: Ensure test entities are purged to avoid dirty state. β
β 4. Use Awaitility for asynchronous events: Poll the database with an SLA window for queue consumers. β
β 5. Parameterize SQL with PreparedStatement: Avoid manual string concatenation and SQL injection flaws. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ