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.
Integration Test
A test that verifies individual modules or components work correctly together, validating interactions between systems between unit tests and E2E tests.
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.
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
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free