πŸ”§ DevOps

Integration Test

Integration Test

A test that verifies individual modules or components work correctly together, validating interactions between systems between unit tests and E2E tests.

πŸ“– Detailed Explanation

Integration Test is a test designed to discover problems that arise when multiple components of software work together. Whereas a unit test verifies the behavior of individual functions or classes, an integration test verifies interactions with external systems, such as database connections, API calls, and message queue communication.

In the test pyramid concept, integration tests sit in the middle layer. Fewer of them are written than unit tests, and they check that the contracts between systems are properly honored. For example, they verify that the request/response format is correct when Service A calls Service B's API, and that database transactions are processed as intended.

There are several approaches to an integration testing strategy. Big Bang is a method that integrates and tests all components at once, Top-Down integrates progressively from upper-level modules to lower-level modules, and Bottom-Up is the opposite. In modern microservice environments, there is a trend of using Contract Testing together with independent integration tests for each service.

As an execution environment, it is widely used to run tests with real databases, Redis, Kafka, and so on launched as Docker containers using Testcontainers, or to mock AWS services with Localstack. In CI/CD pipelines, integration tests are run as a separate stage after unit tests, providing fast feedback on failure.

πŸ’» Code Example

Python + pytest + Testcontainers integration test

import pytest
from testcontainers.postgres import PostgresContainer
from testcontainers.redis import RedisContainer
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
import redis

# μ‹€μ œ PostgreSQL μ»¨ν…Œμ΄λ„ˆλ₯Ό μ‚¬μš©ν•œ 톡합 ν…ŒμŠ€νŠΈ
class TestUserRepository:
    """μ‚¬μš©μž μ €μž₯μ†Œ 톡합 ν…ŒμŠ€νŠΈ - μ‹€μ œ DB 연동"""

    @pytest.fixture(scope="class")
    def postgres_container(self):
        """ν…ŒμŠ€νŠΈμš© PostgreSQL μ»¨ν…Œμ΄λ„ˆ μ‹œμž‘"""
        with PostgresContainer("postgres:15-alpine") as postgres:
            yield postgres

    @pytest.fixture(scope="class")
    def db_session(self, postgres_container):
        """λ°μ΄ν„°λ² μ΄μŠ€ μ„Έμ…˜ 생성"""
        engine = create_engine(postgres_container.get_connection_url())

        # μŠ€ν‚€λ§ˆ μ΄ˆκΈ°ν™”
        with engine.connect() as conn:
            conn.execute(text("""
                CREATE TABLE IF NOT EXISTS users (
                    id SERIAL PRIMARY KEY,
                    email VARCHAR(255) UNIQUE NOT NULL,
                    name VARCHAR(100) NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """))
            conn.commit()

        Session = sessionmaker(bind=engine)
        return Session()

    def test_create_and_retrieve_user(self, db_session):
        """μ‚¬μš©μž 생성 및 쑰회 톡합 ν…ŒμŠ€νŠΈ"""
        # Given: μƒˆλ‘œμš΄ μ‚¬μš©μž 정보
        user_email = "test@example.com"
        user_name = "ν…ŒμŠ€νŠΈ μ‚¬μš©μž"

        # When: μ‚¬μš©μž 생성
        db_session.execute(
            text("INSERT INTO users (email, name) VALUES (:email, :name)"),
            {"email": user_email, "name": user_name}
        )
        db_session.commit()

        # Then: μƒμ„±λœ μ‚¬μš©μž 쑰회 확인
        result = db_session.execute(
            text("SELECT * FROM users WHERE email = :email"),
            {"email": user_email}
        ).fetchone()

        assert result is not None
        assert result.email == user_email
        assert result.name == user_name

    def test_duplicate_email_fails(self, db_session):
        """쀑볡 이메일 등둝 μ‹€νŒ¨ ν…ŒμŠ€νŠΈ"""
        from sqlalchemy.exc import IntegrityError

        email = "duplicate@example.com"

        # 첫 번째 μ‚¬μš©μž 등둝
        db_session.execute(
            text("INSERT INTO users (email, name) VALUES (:email, :name)"),
            {"email": email, "name": "First User"}
        )
        db_session.commit()

        # 같은 μ΄λ©”μΌλ‘œ 두 번째 등둝 μ‹œλ„
        with pytest.raises(IntegrityError):
            db_session.execute(
                text("INSERT INTO users (email, name) VALUES (:email, :name)"),
                {"email": email, "name": "Second User"}
            )
            db_session.commit()


# Redis μΊμ‹œ 톡합 ν…ŒμŠ€νŠΈ
class TestCacheService:
    """μΊμ‹œ μ„œλΉ„μŠ€ 톡합 ν…ŒμŠ€νŠΈ - μ‹€μ œ Redis 연동"""

    @pytest.fixture(scope="class")
    def redis_container(self):
        """ν…ŒμŠ€νŠΈμš© Redis μ»¨ν…Œμ΄λ„ˆ μ‹œμž‘"""
        with RedisContainer("redis:7-alpine") as redis_cont:
            yield redis_cont

    @pytest.fixture
    def redis_client(self, redis_container):
        """Redis ν΄λΌμ΄μ–ΈνŠΈ 생성"""
        client = redis.Redis(
            host=redis_container.get_container_host_ip(),
            port=redis_container.get_exposed_port(6379),
            decode_responses=True
        )
        yield client
        client.flushall()  # ν…ŒμŠ€νŠΈ ν›„ 정리

    def test_cache_set_and_get(self, redis_client):
        """μΊμ‹œ μ €μž₯ 및 쑰회 ν…ŒμŠ€νŠΈ"""
        # Given
        cache_key = "user:123:profile"
        cache_value = '{"id": 123, "name": "Test User"}'

        # When
        redis_client.setex(cache_key, 3600, cache_value)

        # Then
        result = redis_client.get(cache_key)
        assert result == cache_value

    def test_cache_expiration(self, redis_client):
        """μΊμ‹œ 만료 ν…ŒμŠ€νŠΈ"""
        import time

        # Given: 1초 TTL μΊμ‹œ
        cache_key = "temp:data"
        redis_client.setex(cache_key, 1, "temporary")

        # When: 1.5초 λŒ€κΈ°
        time.sleep(1.5)

        # Then: μΊμ‹œ 만료됨
        assert redis_client.get(cache_key) is None


# API 톡합 ν…ŒμŠ€νŠΈ 예제 (FastAPI + httpx)
import httpx
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/api/health")
def health_check():
    return {"status": "healthy"}

@app.post("/api/users")
def create_user(email: str, name: str):
    return {"id": 1, "email": email, "name": name}


class TestAPIIntegration:
    """API μ—”λ“œν¬μΈνŠΈ 톡합 ν…ŒμŠ€νŠΈ"""

    @pytest.fixture
    def client(self):
        return TestClient(app)

    def test_health_endpoint(self, client):
        """ν—¬μŠ€μ²΄ν¬ API ν…ŒμŠ€νŠΈ"""
        response = client.get("/api/health")

        assert response.status_code == 200
        assert response.json()["status"] == "healthy"

    def test_create_user_api(self, client):
        """μ‚¬μš©μž 생성 API 톡합 ν…ŒμŠ€νŠΈ"""
        response = client.post(
            "/api/users",
            params={"email": "new@example.com", "name": "New User"}
        )

        assert response.status_code == 200
        data = response.json()
        assert data["email"] == "new@example.com"
        assert "id" in data

πŸ—£οΈ How It's Said in Practice

QA Engineer "Did you run integration tests with the order service after the payment module change? Last time the API spec changed and we had an outage after deployment."
Backend Developer "Yes, I tested by launching a real PostgreSQL and Redis with Testcontainers. The payment transaction rollback scenario is covered too."
Tech Lead "Good. If the integration test run time gets a bit long in CI, let's separate it from the unit test stage and run them in parallel."
Interviewer "Please explain the difference between unit tests and integration tests, and when to use each."
Candidate "Unit tests mock external dependencies to quickly verify the logic of a single function or class, while integration tests verify interactions with real databases or external APIs. Following the test pyramid principle, I write many unit tests and focus integration tests on key scenarios. I prefer to run integration tests by launching real infrastructure with Docker using Testcontainers."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer "This test mocks the external API call, so how do you verify that the API spec is actually correct?"
Author "I added a separate Contract Test. I wrote a Consumer-Driven Contract test with Pact to verify that the spec matches between the API provider and consumer. Mocking is for unit tests, and the integration tests call the actual staging environment API."

⚠️ Cautions

  • Test isolation: Because integration tests share external resources, data interference can occur between tests. Clean up data before and after each test (setUp/tearDown) and use transaction rollback.
  • Managing execution time: Integration tests are slower than unit tests. Consider running them in parallel in CI, or a strategy of running only the tests related to changed modules. The full test suite can be run in the nightly build.
  • Environment consistency: You must use the same versions of databases, message queues, and so on in the local and CI environments. Manage the environment consistently with Docker Compose or Testcontainers.

πŸ“š Learn More