🟢
Updated recently
Last updated:

Quick Answer: Automate database testing by: (1) connecting via JDBC (Java) or psycopg2/sqlalchemy (Python), (2) executing test queries, (3) asserting expected results, (4) cleaning up test data after each test.

Why Automate Database Testing?

API tests verify correct responses. Database tests verify data is correctly stored, updated, and deleted. Both are needed for complete backend validation.

Database Testing with Python

import psycopg2
import pytest

@pytest.fixture
def db_connection():
    conn = psycopg2.connect(host="localhost", database="test_db",
                            user="test_user", password="test_pass")
    yield conn
    conn.close()

def test_user_created(db_connection):
    cursor = db_connection.cursor()
    cursor.execute("SELECT * FROM users WHERE email = '[email protected]'")
    user = cursor.fetchone()
    assert user is not None
    assert user[1] == "Test User"

Database Testing with Java (JDBC)

import java.sql.*;

public class DatabaseTest {
    Connection conn;

    @BeforeEach
    void setup() throws SQLException {
        conn = DriverManager.getConnection(
            "jdbc:postgresql://localhost:5432/test_db", "test_user", "test_pass");
    }

    @Test
    void testUserExists() throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(
            "SELECT * FROM users WHERE email = '[email protected]'");
        assertTrue(rs.next());
        assertEquals("Test User", rs.getString("name"));
    }
}

Common Database Test Scenarios

  • Data integrity: Verify constraints (NOT NULL, UNIQUE, FOREIGN KEY)
  • Transaction testing: Verify ACID properties
  • Data migration: Verify schema changes preserve data
  • Performance: Verify query execution times

Training Resources

Master test automation with SkilBrill Selenium with Java Training.

FAQ

Should I test the database or just the API?

Both. API tests verify the interface; database tests verify data persistence.