Purpose & When-To-Use
Trigger conditions:
- Designing integration tests for microservices that interact with databases and external APIs
- Validating API contracts between services in a distributed system
- Setting up isolated test environments with real database instances
- Mocking external third-party services (payment gateways, notification services, webhooks)
- Testing message-driven architectures (Kafka, RabbitMQ, SQS)
- Validating database transactions, migrations, and data consistency
- Replacing brittle end-to-end tests with focused integration tests
Use this skill when you need to test service boundaries, validate integration points, ensure contract compatibility, or create reproducible test environments with real infrastructure dependencies.
Pre-Checks
Before execution, verify:
- Time normalization:
NOW_ET = 2025-10-26T02:31:19-04:00 (NIST/time.gov semantics, America/New_York)
- Input schema validation:
services is non-empty array with service names
dependencies includes keys: databases, apis, queues, or caches
test_scope is one of: smoke, happy-path, edge-cases, full
tech_stack (if provided) contains valid testing framework identifiers
- Source freshness: All cited sources accessed on
NOW_ET; verify links resolve
- Docker availability: Confirm Docker/Podman is available for TestContainers usage
- Dependency compatibility: Verify mock tools support required protocols (REST, gRPC, GraphQL)
Abort conditions:
- Services description lacks clear dependency relationships
- Dependencies include proprietary systems without mock/stub capabilities
- Test scope is contradictory (e.g., "full coverage" with "no database access")
- Infrastructure constraints prevent container usage
Procedure
T1: Fast Path (≤2k tokens)
Goal: Generate basic integration test structure with database fixture and API mock.
Identify integration points:
- Database dependencies (PostgreSQL, MySQL, MongoDB, Redis)
- External HTTP APIs (REST, GraphQL)
- Message queues (Kafka, RabbitMQ, SQS)
- Third-party services (Stripe, Twilio, SendGrid)
Select testing strategy (based on [TestContainers Patterns](https://testcontainers.com/, accessed 2025-10-26)):
- Database: TestContainers (real DB instance) vs. in-memory (H2, SQLite)
- HTTP APIs: WireMock for deterministic responses
- Queues: TestContainers with real broker for integration, mock for unit-level
- Third-party: Mock webhooks and API responses
Generate basic test structure:
// Example: Spring Boot integration test
@SpringBootTest
@Testcontainers
class PaymentServiceIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15-alpine");
@Test
void processPayment_withValidCard_createsTransaction() {
// Arrange: seed database, mock Stripe
// Act: call PaymentService
// Assert: verify database state and external call
}
}
Output test scenario outline:
- Test case name and description
- Required fixtures (database records)
- Mock configurations (API endpoints)
- Expected outcomes (database state, external calls)
Token budget: ≤2k tokens
T2: Extended Analysis (≤6k tokens)
Goal: Generate complete test scenarios, fixtures, mocks, and environment setup.
Create database fixtures (following [pytest fixtures](https://pytest.org/, accessed 2025-10-26) and [Spring Test](https://docs.spring.io/spring-boot/reference/testing/index.html, accessed 2025-10-26) patterns):
- Seed data SQL/JSON files for initial state
- Factory functions for test data generation
- Cleanup strategies (transaction rollback, container disposal)
- Migration application in test environment
Configure service mocks (using [WireMock](https://wiremock.org/, accessed 2025-10-26)):
- Stub external API responses (success, failure, timeout)
- Webhook simulation for callbacks
- Request matching and verification
- State-based mocking for complex scenarios
Setup test environment:
- Docker Compose: Multi-container setup for CI/local development
- TestContainers: Programmatic container lifecycle in tests
- Environment variables: Database URLs, API keys (test mode)
- Network configuration: Service discovery, port mapping
Design contract tests (following [Pact](https://pact.io/, accessed 2025-10-26) consumer-driven contract testing):
- Consumer-side pact generation
- Provider-side verification
- Contract versioning and evolution
- Pact broker integration for sharing contracts
Generate test scenarios:
- Happy path: Successful integration with all dependencies
- Error handling: Database failures, API timeouts, invalid responses
- Edge cases: Concurrent requests, large payloads, rate limiting
- Data consistency: Transaction rollback, eventual consistency
Token budget: ≤6k tokens total (including T1)
T3: Deep Dive (≤12k tokens)
Goal: Add advanced integration patterns, performance considerations, and CI/CD integration.
Advanced testing patterns:
- Saga testing: Multi-service transaction coordination
- Event-driven testing: Message production and consumption verification
- Cache invalidation: Redis/Memcached interaction testing
- Schema evolution: Database migration testing with Flyway/Liquibase
Performance and reliability:
- Connection pool configuration for test databases
- Test parallelization with isolated database schemas
- Flaky test mitigation (retry policies, wait strategies)
- Resource cleanup and leak detection
CI/CD integration:
- Container registry pre-pulling for faster test execution
- Parallel test execution with Gradle/Maven/pytest-xdist
- Test result aggregation and reporting
- Integration test stage in pipeline (post-unit, pre-E2E)
Documentation and maintenance:
- Test data management strategy
- Mock service update procedures
- Contract versioning guidelines
- Troubleshooting guide for common failures
Token budget: ≤12k tokens total (including T1 + T2)
Decision Rules
Test scope adjustments:
- Smoke: 3-5 critical path tests with minimal fixtures
- Happy-path: 10-15 tests covering primary workflows
- Edge-cases: Add 20-30 tests for error scenarios, boundaries, concurrency
- Full: Include performance, security, and chaos scenarios
Database strategy selection:
Mock vs. Real service:
- Mock external APIs: Payment gateways, email providers, SMS services
- Use real services (containerized): Databases, message queues, caches
- Use contract tests: For services you control in same organization
- Use sandbox/test environments: For third-party services with test modes
Effort estimation (per integration point):
- Basic integration test: 2-4 hours
- Complex multi-service scenario: 6-12 hours
- Contract test setup: 4-8 hours
- TestContainers environment: 1-3 hours (initial), 30min (per additional service)
Stop conditions:
- If no external dependencies exist: redirect to unit testing
- If only UI-level integration needed: redirect to E2E testing skill
- If services lack clear boundaries: recommend architecture refactoring first
Output Contract
Required fields (all outputs):
interface IntegrationTestDesign {
test_scenarios: Array<{
name: string;
description: string;
services_under_test: string[];
dependencies: string[];
test_steps: Array<{
step: string;
action: string;
expected_outcome: string;
}>;
fixtures_required: string[];
mocks_required: string[];
}>;
fixtures: {
database_seeds: Array<{
table: string;
format: "sql" | "json" | "yaml";
content: string;
}>;
factory_functions?: string; // Code snippet
};
environment_setup: {
format: "docker-compose" | "testcontainers" | "kubernetes";
content: string; // YAML or code
setup_instructions: string;
};
contract_tests?: Array<{
consumer: string;
provider: string;
contract_format: "pact" | "spring-cloud-contract" | "openapi";
interactions: Array<{
description: string;
request: object;
response: object;
}>;
}>;
mock_configurations: Array<{
service_name: string;
tool: "wiremock" | "mockserver" | "nock" | "responses";
stubs: Array<{
endpoint: string;
method: string;
response_body: object;
status_code: number;
}>;
}>;
}
Format:
test_scenarios: Array of objects with consistent structure
fixtures: SQL/JSON with valid syntax
environment_setup: Valid Docker Compose YAML or TestContainers code
contract_tests: Pact-compatible JSON or Spring Cloud Contract DSL
Validation:
- All referenced fixtures exist in fixtures section
- All mocked services are in dependencies
- Database schema matches application models
- Port mappings don't conflict
Examples
Example 1: Payment API Integration Test (T2)
INPUT:
services: ["payment-api"]
dependencies: {databases: ["postgres"], apis: ["stripe"]}
test_scope: "happy-path"
OUTPUT:
test_scenarios:
- name: "Process payment and store transaction"
test_steps:
- "Setup: Start PostgreSQL, seed users, stub Stripe API"
- "Execute: POST /payments with valid card"
- "Assert: 201 response, transaction in DB, Stripe called"
fixtures:
database_seeds:
- table: "users"
content: "INSERT INTO users (id, email) VALUES (1, 'test@example.com');"
mock_configurations:
- service_name: "stripe"
tool: "wiremock"
stubs: [{endpoint: "/v1/charges", status: 200}]
Quality Gates
Token budgets (mandatory):
- T1 ≤ 2k tokens (basic integration test structure)
- T2 ≤ 6k tokens (complete fixtures + mocks + environment)
- T3 ≤ 12k tokens (advanced patterns + CI/CD integration)
Safety checks:
Auditability:
Determinism:
Validation checklist:
Resources
Primary sources (accessed 2025-10-26):
TestContainers: https://testcontainers.com/
Lightweight, throwaway instances of databases, message brokers, and other services for integration testing.
WireMock: https://wiremock.org/
Flexible API mocking tool for HTTP-based services with request matching and response stubbing.
Pact: https://pact.io/
Consumer-driven contract testing framework for validating API interactions between services.
Spring Boot Testing: https://docs.spring.io/spring-boot/reference/testing/index.html
Official Spring Boot testing documentation covering @SpringBootTest, MockMvc, and TestContainers integration.
pytest: https://pytest.org/
Python testing framework with powerful fixtures and parametrization for integration testing.
Additional templates:
- See
examples/payment-integration-test.java for complete Java example
- See
resources/docker-compose-test.yml for multi-service test environment
- See
resources/pact-contract-example.json for contract test template
Related skills:
testing-strategy-composer (for overall testing strategy)
api-design-validator (for API contract design)
database-optimization-analyzer (for test database performance)
End of SKILL.md
1---2name: integration-testing-designer3description: Design integration test scenarios with database fixtures, external service mocks, contract testing, and test environment setup for microservices and APIs.4license: MIT5---67## Purpose & When-To-Use89**Trigger conditions:**1011- Designing integration tests for microservices that interact with databases and external APIs12- Validating API contracts between services in a distributed system13- Setting up isolated test environments with real database instances14- Mocking external third-party services (payment gateways, notification services, webhooks)15- Testing message-driven architectures (Kafka, RabbitMQ, SQS)16- Validating database transactions, migrations, and data consistency17- Replacing brittle end-to-end tests with focused integration tests1819**Use this skill when** you need to test service boundaries, validate integration points, ensure contract compatibility, or create reproducible test environments with real infrastructure dependencies.2021---2223## Pre-Checks2425**Before execution, verify:**26271. **Time normalization**: `NOW_ET = 2025-10-26T02:31:19-04:00` (NIST/time.gov semantics, America/New_York)282. **Input schema validation**:29 - `services` is non-empty array with service names30 - `dependencies` includes keys: `databases`, `apis`, `queues`, or `caches`31 - `test_scope` is one of: smoke, happy-path, edge-cases, full32 - `tech_stack` (if provided) contains valid testing framework identifiers333. **Source freshness**: All cited sources accessed on `NOW_ET`; verify links resolve344. **Docker availability**: Confirm Docker/Podman is available for TestContainers usage355. **Dependency compatibility**: Verify mock tools support required protocols (REST, gRPC, GraphQL)3637**Abort conditions:**3839- Services description lacks clear dependency relationships40- Dependencies include proprietary systems without mock/stub capabilities41- Test scope is contradictory (e.g., "full coverage" with "no database access")42- Infrastructure constraints prevent container usage4344---4546## Procedure4748### T1: Fast Path (≤2k tokens)4950**Goal**: Generate basic integration test structure with database fixture and API mock.51521. **Identify integration points**:53 - Database dependencies (PostgreSQL, MySQL, MongoDB, Redis)54 - External HTTP APIs (REST, GraphQL)55 - Message queues (Kafka, RabbitMQ, SQS)56 - Third-party services (Stripe, Twilio, SendGrid)57582. **Select testing strategy** (based on [TestContainers Patterns](https://testcontainers.com/, accessed 2025-10-26)):59 - **Database**: TestContainers (real DB instance) vs. in-memory (H2, SQLite)60 - **HTTP APIs**: WireMock for deterministic responses61 - **Queues**: TestContainers with real broker for integration, mock for unit-level62 - **Third-party**: Mock webhooks and API responses63643. **Generate basic test structure**:65 ```java66 // Example: Spring Boot integration test67 @SpringBootTest68 @Testcontainers69 class PaymentServiceIntegrationTest {70 @Container71 static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15-alpine");7273 @Test74 void processPayment_withValidCard_createsTransaction() {75 // Arrange: seed database, mock Stripe76 // Act: call PaymentService77 // Assert: verify database state and external call78 }79 }80 ```81824. **Output test scenario outline**:83 - Test case name and description84 - Required fixtures (database records)85 - Mock configurations (API endpoints)86 - Expected outcomes (database state, external calls)8788**Token budget**: ≤2k tokens8990---9192### T2: Extended Analysis (≤6k tokens)9394**Goal**: Generate complete test scenarios, fixtures, mocks, and environment setup.95965. **Create database fixtures** (following [pytest fixtures](https://pytest.org/, accessed 2025-10-26) and [Spring Test](https://docs.spring.io/spring-boot/reference/testing/index.html, accessed 2025-10-26) patterns):97 - Seed data SQL/JSON files for initial state98 - Factory functions for test data generation99 - Cleanup strategies (transaction rollback, container disposal)100 - Migration application in test environment1011026. **Configure service mocks** (using [WireMock](https://wiremock.org/, accessed 2025-10-26)):103 - Stub external API responses (success, failure, timeout)104 - Webhook simulation for callbacks105 - Request matching and verification106 - State-based mocking for complex scenarios1071087. **Setup test environment**:109 - **Docker Compose**: Multi-container setup for CI/local development110 - **TestContainers**: Programmatic container lifecycle in tests111 - **Environment variables**: Database URLs, API keys (test mode)112 - **Network configuration**: Service discovery, port mapping1131148. **Design contract tests** (following [Pact](https://pact.io/, accessed 2025-10-26) consumer-driven contract testing):115 - Consumer-side pact generation116 - Provider-side verification117 - Contract versioning and evolution118 - Pact broker integration for sharing contracts1191209. **Generate test scenarios**:121 - **Happy path**: Successful integration with all dependencies122 - **Error handling**: Database failures, API timeouts, invalid responses123 - **Edge cases**: Concurrent requests, large payloads, rate limiting124 - **Data consistency**: Transaction rollback, eventual consistency125126**Token budget**: ≤6k tokens total (including T1)127128---129130### T3: Deep Dive (≤12k tokens)131132**Goal**: Add advanced integration patterns, performance considerations, and CI/CD integration.13313410. **Advanced testing patterns**:135 - **Saga testing**: Multi-service transaction coordination136 - **Event-driven testing**: Message production and consumption verification137 - **Cache invalidation**: Redis/Memcached interaction testing138 - **Schema evolution**: Database migration testing with Flyway/Liquibase13914011. **Performance and reliability**:141 - Connection pool configuration for test databases142 - Test parallelization with isolated database schemas143 - Flaky test mitigation (retry policies, wait strategies)144 - Resource cleanup and leak detection14514612. **CI/CD integration**:147 - Container registry pre-pulling for faster test execution148 - Parallel test execution with Gradle/Maven/pytest-xdist149 - Test result aggregation and reporting150 - Integration test stage in pipeline (post-unit, pre-E2E)15115213. **Documentation and maintenance**:153 - Test data management strategy154 - Mock service update procedures155 - Contract versioning guidelines156 - Troubleshooting guide for common failures157158**Token budget**: ≤12k tokens total (including T1 + T2)159160---161162## Decision Rules163164**Test scope adjustments:**165166- **Smoke**: 3-5 critical path tests with minimal fixtures167- **Happy-path**: 10-15 tests covering primary workflows168- **Edge-cases**: Add 20-30 tests for error scenarios, boundaries, concurrency169- **Full**: Include performance, security, and chaos scenarios170171**Database strategy selection:**172173- **Use TestContainers when**:174 - Testing database-specific features (JSON columns, full-text search)175 - Validating complex queries and transactions176 - Testing migrations and schema changes177 - Production database is PostgreSQL, MySQL, MongoDB, or supported DB178179- **Use in-memory database when**:180 - Simple CRUD operations with standard SQL181 - Fast feedback required (unit test-like speed)182 - CI environment has resource constraints183 - Database is abstracted through ORM184185**Mock vs. Real service:**186187- **Mock external APIs**: Payment gateways, email providers, SMS services188- **Use real services (containerized)**: Databases, message queues, caches189- **Use contract tests**: For services you control in same organization190- **Use sandbox/test environments**: For third-party services with test modes191192**Effort estimation** (per integration point):193194- Basic integration test: 2-4 hours195- Complex multi-service scenario: 6-12 hours196- Contract test setup: 4-8 hours197- TestContainers environment: 1-3 hours (initial), 30min (per additional service)198199**Stop conditions:**200201- If no external dependencies exist: redirect to unit testing202- If only UI-level integration needed: redirect to E2E testing skill203- If services lack clear boundaries: recommend architecture refactoring first204205---206207## Output Contract208209**Required fields** (all outputs):210211```typescript212interface IntegrationTestDesign {213 test_scenarios: Array<{214 name: string;215 description: string;216 services_under_test: string[];217 dependencies: string[];218 test_steps: Array<{219 step: string;220 action: string;221 expected_outcome: string;222 }>;223 fixtures_required: string[];224 mocks_required: string[];225 }>;226227 fixtures: {228 database_seeds: Array<{229 table: string;230 format: "sql" | "json" | "yaml";231 content: string;232 }>;233 factory_functions?: string; // Code snippet234 };235236 environment_setup: {237 format: "docker-compose" | "testcontainers" | "kubernetes";238 content: string; // YAML or code239 setup_instructions: string;240 };241242 contract_tests?: Array<{243 consumer: string;244 provider: string;245 contract_format: "pact" | "spring-cloud-contract" | "openapi";246 interactions: Array<{247 description: string;248 request: object;249 response: object;250 }>;251 }>;252253 mock_configurations: Array<{254 service_name: string;255 tool: "wiremock" | "mockserver" | "nock" | "responses";256 stubs: Array<{257 endpoint: string;258 method: string;259 response_body: object;260 status_code: number;261 }>;262 }>;263}264```265266**Format**:267268- `test_scenarios`: Array of objects with consistent structure269- `fixtures`: SQL/JSON with valid syntax270- `environment_setup`: Valid Docker Compose YAML or TestContainers code271- `contract_tests`: Pact-compatible JSON or Spring Cloud Contract DSL272273**Validation**:274275- All referenced fixtures exist in fixtures section276- All mocked services are in dependencies277- Database schema matches application models278- Port mappings don't conflict279280---281282## Examples283284### Example 1: Payment API Integration Test (T2)285286```yaml287INPUT:288 services: ["payment-api"]289 dependencies: {databases: ["postgres"], apis: ["stripe"]}290 test_scope: "happy-path"291292OUTPUT:293 test_scenarios:294 - name: "Process payment and store transaction"295 test_steps:296 - "Setup: Start PostgreSQL, seed users, stub Stripe API"297 - "Execute: POST /payments with valid card"298 - "Assert: 201 response, transaction in DB, Stripe called"299300 fixtures:301 database_seeds:302 - table: "users"303 content: "INSERT INTO users (id, email) VALUES (1, 'test@example.com');"304305 mock_configurations:306 - service_name: "stripe"307 tool: "wiremock"308 stubs: [{endpoint: "/v1/charges", status: 200}]309```310311---312313## Quality Gates314315**Token budgets** (mandatory):316317- T1 ≤ 2k tokens (basic integration test structure)318- T2 ≤ 6k tokens (complete fixtures + mocks + environment)319- T3 ≤ 12k tokens (advanced patterns + CI/CD integration)320321**Safety checks**:322323- [ ] No production credentials in fixtures or mocks324- [ ] No real external API calls (all mocked or sandboxed)325- [ ] Database containers use non-persistent volumes in tests326- [ ] Cleanup code prevents resource leaks327328**Auditability**:329330- [ ] All sources cited with access date = `NOW_ET`331- [ ] Test data generation is deterministic and reproducible332- [ ] Mock responses match actual API documentation333- [ ] Container versions are pinned (not `latest`)334335**Determinism**:336337- [ ] Tests pass consistently with same inputs338- [ ] Database state is reset between tests339- [ ] Time-dependent logic uses fixed test time340- [ ] Random data generation uses fixed seeds341342**Validation checklist**:343344- [ ] Output JSON validates against schema345- [ ] Docker Compose YAML is valid (`docker-compose config`)346- [ ] SQL fixtures execute without errors347- [ ] Mock endpoints match API documentation348- [ ] TestContainers code compiles349350---351352## Resources353354**Primary sources** (accessed 2025-10-26):3553561. **TestContainers**: https://testcontainers.com/357 Lightweight, throwaway instances of databases, message brokers, and other services for integration testing.3583592. **WireMock**: https://wiremock.org/360 Flexible API mocking tool for HTTP-based services with request matching and response stubbing.3613623. **Pact**: https://pact.io/363 Consumer-driven contract testing framework for validating API interactions between services.3643654. **Spring Boot Testing**: https://docs.spring.io/spring-boot/reference/testing/index.html366 Official Spring Boot testing documentation covering @SpringBootTest, MockMvc, and TestContainers integration.3673685. **pytest**: https://pytest.org/369 Python testing framework with powerful fixtures and parametrization for integration testing.370371**Additional templates**:372373- See `examples/payment-integration-test.java` for complete Java example374- See `resources/docker-compose-test.yml` for multi-service test environment375- See `resources/pact-contract-example.json` for contract test template376377**Related skills**:378379- `testing-strategy-composer` (for overall testing strategy)380- `api-design-validator` (for API contract design)381- `database-optimization-analyzer` (for test database performance)382383---384385**End of SKILL.md**