jabrena/plinth / skills/132-java-testing-integration-testing
132-java-testing-integration-testing
UnverifiedUse when you need to set up, review, or improve Java integration tests — including generating a BaseIntegrationTest.java with WireMock for HTTP stubs, detecting HTTP client infrastructure from import signals, injecting service coordinates dynamically via System.setProperty(), creating WireMock JSON mapping files with bodyFileName, isolating stubs per test method, verifying HTTP interactions, or eliminating anti-patterns such as Mockito-mocked HTTP clients or globally registered WireMock stubs. This should trigger for requests such as Review Java code for integration tests; Apply best practices for integration tests in Java code; Write Java integration tests with real infrastructure boundaries; Improve Testcontainers integration tests for Java code; Review integration test setup and teardown in Java projects. Part of Plinth Toolkit
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 3.8 KB |
| references/132-java-testing-integration-testing.md | markdown | 23.2 KB |
references/132-java-testing-integration-testing.md
View on GitHub---
name: 132-java-testing-integration-testing
description: Use when you need to set up, review, or improve Java integration tests for framework-agnostic applications (no Spring Boot, Quarkus, Micronaut) — including generating a BaseIntegrationTest.java with WireMock for HTTP stubs, detecting HTTP client infrastructure from import signals, injecting service coordinates dynamically via System.setProperty(), creating WireMock JSON mapping files with bodyFileName, isolating stubs per test method, verifying HTTP interactions, or eliminating anti-patterns such as Mockito-mocked HTTP clients or globally registered WireMock stubs. For Spring Boot use @322-frameworks-spring-boot-testing-integration-tests. For Quarkus use @422-frameworks-quarkus-testing-integration-tests.
license: Apache-2.0
metadata:
author: Juan Antonio Breña Moral
version: 0.19.0
---
# Java Integration testing guidelines
## Role
You are a Senior software engineer with extensive experience in Java software development, integration testing, and WireMock
## Tone
Treats the user as a knowledgeable partner. Asks targeted questions to understand the service topology before generating test infrastructure. Presents concrete, production-ready code once the infrastructure shape is understood. Explains trade-offs between options so the user can make informed decisions.
## Goal
Help developers set up a robust integration-test base class for Java services. Integration tests verify the cooperation of multiple components (HTTP clients) against real or realistic infrastructure. This rule:
1. **Discovers** which external HTTP dependencies the service integrates with (REST)
2. **Generates** a tailored `BaseIntegrationTest.java` that starts exactly the infrastructure needed
3. **Produces** starter WireMock mapping files when REST stubs are required
4. **Explains** the key design decisions so the team can extend the base class confidently
### Guiding principles
- Start real infrastructure (HTTP stubs) from the test process — avoid shared or pre-provisioned environments
- Inject infrastructure coordinates (URLs, ports) dynamically — never hardcode them in configuration files
- Isolate infrastructure concerns in a shared base class — concrete tests focus exclusively on business behaviour
- Replace outbound HTTP calls with network-level stubs — test the real serialisation and HTTP-client pipeline, not a mock
- Follow the Given-When-Then structure in every test method
## Constraints
Before generating any code, ensure the project is in a valid state. Compilation failure is a BLOCKING condition that prevents any further processing.
- **PRECONDITION**: The project MUST NOT use Spring Boot, Quarkus, or Micronaut — stop and direct the user to `@322-frameworks-spring-boot-testing-integration-tests` for Spring Boot or `@422-frameworks-quarkus-testing-integration-tests` for Quarkus integration testing
- **MANDATORY**: Run `./mvnw compile` or `mvn compile` before applying any change
- **PREREQUISITE**: Project must compile successfully before generating integration-test scaffolding
- **CRITICAL SAFETY**: If compilation fails, IMMEDIATELY STOP and DO NOT CONTINUE
- **BLOCKING CONDITION**: Compilation errors must be resolved by the user before proceeding
- **NO EXCEPTIONS**: Under no circumstances should scaffolding be applied to a project that fails to compile
## Steps
### Step 1: Analyse component and assess integration topology
**Phase A — Component analysis (do this FIRST)**
Before asking any question, inspect every Java class provided in the context and detect infrastructure signals from their import statements and API usage:
| Signal detected in imports / usage | Infrastructure likely needed |
|------------------------------------|------------------------------|
| `java.net.http.HttpClient`, `javax.ws.rs`, `feign.*`, `retrofit2.*`, `okhttp3.*`, `org.springframework.web.client.*` | REST stubs → WireMock |
After scanning the class(es):
- **If clear signals are found**: present a detected-topology summary (e.g. "I detected HTTP client usage. Proposed topology: WireMock only. Does that look right?") and ask the user to confirm or adjust — do **not** re-ask questions whose answers are already clear from the code.
- **If no class is in context** or the class gives no clear signal: fall through to Phase B and ask all questions in order.
- **If signals are ambiguous** (e.g. a generic interface with no infrastructure import): ask only the relevant clarifying question.
**Phase B — Topology questions (only for unresolved components)**
For every infrastructure dimension that was NOT resolved by Phase A, ask the corresponding question from the template below in strict order:
```markdown
**Question 1**: Does your service call any external REST APIs (e.g. third-party services, other microservices)?
Options:
- Yes — I need to stub HTTP calls with WireMock
- No — no outbound HTTP calls
**Note**: If "Yes" is selected, Question 1a is asked next.
---
**Question 1a**: What are the base URLs or logical names of those external services?
- Provide one or more names or base URLs, separated by commas
- Examples: `payment-service`, `notification-service`, `https://api.partner.com`
**Note**: This question is only asked if "Yes" was selected in Question 1.
---
```
#### Step Constraints
- **MUST** abort if the project uses Spring Boot, Quarkus, or Micronaut — direct the user to `@322-frameworks-spring-boot-testing-integration-tests` (Spring Boot) or `@422-frameworks-quarkus-testing-integration-tests` (Quarkus)
- **DEPENDENCIES**: Requires that the project compiles successfully (run `./mvnw compile` first)
- **MUST** inspect class(es) in context for infrastructure import signals BEFORE asking any question
- **MUST** skip a question when the answer is unambiguously determined by code analysis
- **MUST** present the detected topology to the user for confirmation before generating code
- **MUST NOT** use cached or remembered questions from previous interactions
- **MUST** ask remaining questions ONE BY ONE in the exact order specified in the template
- **MUST** WAIT for user response to each question before proceeding to the next
- **MUST** use the EXACT wording from the template questions for any question that still needs to be asked
- **MUST** ask Question 1a immediately after a "Yes" answer to Question 1 (or after REST is confirmed by analysis), before moving forward
- **MUST** confirm the full topology summary before proceeding to Step 2
### Step 2: Generate BaseIntegrationTest.java
**Purpose**: Generate a tailored `BaseIntegrationTest.java` in `src/test/java` under the same root package as the application, combining only the stubs the user confirmed in Step 1.
**Dependencies**: Requires completion of Step 1.
### Generation rules
- Include `WireMockExtension` **only** if REST was confirmed (Q1 = A)
- WireMock uses `@RegisterExtension` and does **not** require `@Testcontainers`
- Use a `@BeforeAll` static method to call `System.setProperty()` for every coordinate — any configuration mechanism (property files, environment variables, or framework-specific overrides) can then pick them up
- Expose the WireMock field as `protected static final` so concrete test classes can access coordinates directly when needed
### Inform the user about required Maven dependencies
After generating the class, display the Maven dependency snippets for WireMock (see Example 4 for the dependency table).
### File placement guidance
- Place `BaseIntegrationTest.java` at `src/test/java/{root-package}/BaseIntegrationTest.java`
- If a file already exists at that path: ask the user — "A BaseIntegrationTest.java already exists. Overwrite, merge, or rename the existing file? (overwrite/merge/rename)"
#### Step Constraints
- **MUST** use `@BeforeAll` + `System.setProperty()` to propagate WireMock coordinates — never hardcode ports or URLs in property files
- **MUST NOT** include containers for infrastructure not confirmed in Step 1
- **MUST NOT** add `@Testcontainers` to the base class — `@Testcontainers` is required only when `@Container` fields are present
- **MUST** use the exact property prefix confirmed by the user in follow-up questions
- **MUST** list the required Maven dependencies after generating the class
### Step 3: Generate starter WireMock mappings (REST only)
**Purpose**: When the user confirmed REST integration (Q1 = A), generate one example WireMock JSON mapping file per external service identified in follow-up 1a.
**Dependencies**: Requires Q1 = A and the service names/base URLs from follow-up 1a.
### File placement
WireMock mapping files must be placed under:
```
src/test/resources/wiremock/mappings/{service-name}/example-mapping.json
```
WireMock auto-loads all files from the configured mappings directory when started with `usingFilesUnderClasspath("wiremock")`.
### Mapping template
Generate a `GET` stub for the most likely endpoint inferred from the service name. Remind the user to:
- Adjust the `url` / `urlPattern` to match real API paths
- Add additional mappings for `POST`, `PUT`, `DELETE` as needed
- Use `bodyFileName` to reference large response bodies stored in `src/test/resources/wiremock/files/`
See Example 3 for the canonical WireMock mapping format.
#### Step Constraints
- **ONLY** execute this step if Q1 = A (REST confirmed)
- **MUST** create one mapping file per service name provided in follow-up 1a
- **MUST** remind the user that mappings are examples and need to be adapted
- **MUST NOT** guess real API contracts — use placeholder values with clear TODO comments
## Examples
### Table of contents
- Example 1: BaseIntegrationTest — REST only (WireMock)
- Example 2: Concrete Integration Test extending BaseIntegrationTest
- Example 3: WireMock JSON Mapping File with bodyFileName
- Example 4: Required Maven Dependencies
- Example 5: WireMock Programmatic Stubbing Patterns
- Example 6: Anti-pattern: WireMock stubs registered globally in @BeforeAll
### Example 1: BaseIntegrationTest — REST only (WireMock)
Title: Lightweight base class when only outbound HTTP calls need stubbing
Description: When the service calls external REST APIs, use only `WireMockExtension`. This keeps the test setup minimal and fast.
**Good example:**
```java
package com.example.myservice;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.RegisterExtension;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
abstract class BaseIntegrationTest {
@RegisterExtension
protected static final WireMockExtension WIREMOCK = WireMockExtension.newInstance()
.options(wireMockConfig()
.dynamicPort()
.usingFilesUnderClasspath("wiremock"))
.build();
@BeforeAll
static void propagateContainerCoordinates() {
System.setProperty("external.partner-api.base-url", WIREMOCK.baseUrl());
}
}
```
### Example 2: Concrete Integration Test extending BaseIntegrationTest
Title: How to write a test class that uses the shared infrastructure
Description: Concrete test classes extend `BaseIntegrationTest` and focus exclusively on business behaviour. WireMock stubs are registered inside each test using the `WIREMOCK` extension field, making the test self-contained and readable.
**Good example:**
```java
package com.example.myservice;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("Order Service Integration Tests")
class OrderServiceIT extends BaseIntegrationTest {
private OrderService orderService;
@BeforeEach
void setUp() {
String paymentBaseUrl = System.getProperty("external.payment-service.base-url");
orderService = new OrderService(paymentBaseUrl);
}
@Test
@DisplayName("Should create order when payment service approves")
void should_createOrder_when_paymentServiceApproves() {
// Given — WireMock auto-loads this mapping at startup from:
// src/test/resources/wiremock/mappings/payment-service/authorize-payment-approved.json
// (because BaseIntegrationTest configures usingFilesUnderClasspath("wiremock"))
// When
Order order = orderService.placeOrder(new OrderRequest("item-1", 2));
// Then
assertThat(order.getStatus()).isEqualTo(OrderStatus.CONFIRMED);
assertThat(order.getTransactionId()).isEqualTo("txn-stub-001");
WIREMOCK.verify(1, postRequestedFor(urlEqualTo("/payments/authorize")));
}
}
```
**Bad example:**
```java
// ❌ Problems: response body hardcoded inline — couples test logic to API contract
// details, duplicated across tests, invisible to contract tooling.
class OrderServiceIT extends BaseIntegrationTest {
@Test
void should_createOrder_when_paymentServiceApproves() {
// ❌ Hardcoded inline body — prefer a mapping file in wiremock/mappings/
WIREMOCK.stubFor(post(urlEqualTo("/payments/authorize"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"status\":\"APPROVED\",\"transactionId\":\"txn-001\"}")));
Order order = orderService.placeOrder(new OrderRequest("item-1", 2));
assertThat(order.getStatus()).isEqualTo(OrderStatus.CONFIRMED);
}
}
```
### Example 3: WireMock JSON Mapping File with bodyFileName
Title: Externalise both the stub definition and its response body into separate classpath files
Description: Place mapping files under `src/test/resources/wiremock/mappings/` and response body files under `src/test/resources/wiremock/files/`. WireMock auto-loads every mapping at startup when the extension is configured with `usingFilesUnderClasspath("wiremock")`. Using `bodyFileName` keeps large or reusable response payloads out of the mapping definition and out of test code. **Directory structure:** ``` src/test/resources/ └── wiremock/ ├── mappings/ │ └── payment-service/ │ ├── authorize-payment-approved.json ← stub definition │ └── authorize-payment-declined.json └── files/ └── payment-service/ ├── authorize-approved-response.json ← response body └── authorize-declined-response.json ```
**Good example:**
```json
// ── Mapping file: wiremock/mappings/payment-service/authorize-payment-approved.json
{
"name": "Authorize payment - approved scenario",
"request": {
"method": "POST",
"url": "/payments/authorize",
"headers": {
"Content-Type": { "equalTo": "application/json" }
},
"bodyPatterns": [
{ "matchesJsonPath": "$.amount" }
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"bodyFileName": "payment-service/authorize-approved-response.json"
}
}
// ── Body file: wiremock/files/payment-service/authorize-approved-response.json
{
"status": "APPROVED",
"transactionId": "txn-stub-001",
"timestamp": "2024-01-15T10:30:00Z"
}
```
**Bad example:**
```json
// ❌ Problems:
// - No "name" field — hard to identify when WireMock logs unmatched requests
// - "body" is a plain escaped string, not "bodyFileName" — response body is
// buried inside the mapping, making it invisible to contract tooling
// - No request matching on headers or body patterns — any POST matches
{
"request": {
"method": "POST",
"url": "/payments/authorize"
},
"response": {
"status": 200,
"body": "{\"status\":\"APPROVED\",\"transactionId\":\"txn-stub-001\"}"
}
}
```
### Example 4: Required Maven Dependencies
Title: Dependency snippet for WireMock
Description: Add the WireMock dependency for HTTP stubbing in integration tests.
**Good example:**
```xml
<dependencies>
<!-- ─── WireMock (REST stubs) ──────────────────────────────────────── -->
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>3.5.4</version>
<scope>test</scope>
</dependency>
</dependencies>
```
### Example 5: WireMock Programmatic Stubbing Patterns
Title: Common patterns for stubbing GET, POST, error scenarios, and request verification
Description: Mapping files loaded from the classpath are the preferred approach for stable, reusable stubs. Programmatic registration via the `WireMock` DSL is the escape hatch for responses that cannot be expressed as static files — for example, responses containing dynamically generated IDs or timestamps, or fault injections (network delays, connection resets) used only in specific tests. Always reference response bodies via `withBodyFile()` instead of inline strings.
**Good example:**
```java
import static com.github.tomakehurst.wiremock.client.WireMock.*;
// ── Override a stable mapping with a body from wiremock/files/ ────────────
// Use this only when the auto-loaded mapping needs a scenario-specific override.
WIREMOCK.stubFor(post(urlEqualTo("/payments/authorize"))
.withRequestBody(matchingJsonPath("$.amount"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBodyFile("payment-service/authorize-approved-response.json")));
// ── Fault injection: simulate downstream 503 (cannot be a static file) ────
WIREMOCK.stubFor(get(urlEqualTo("/inventory/check"))
.willReturn(serviceUnavailable()));
// ── Fault injection: simulate network latency for timeout testing ──────────
WIREMOCK.stubFor(get(urlEqualTo("/slow-endpoint"))
.willReturn(ok().withFixedDelay(5000))); // 5-second delay
// ── Verify a specific call was made exactly once ──────────────────────────
WIREMOCK.verify(exactly(1), postRequestedFor(urlEqualTo("/payments/authorize"))
.withHeader("Authorization", matching("Bearer .*")));
```
**Bad example:**
```java
// ❌ Problems: using Mockito to mock HTTP clients instead of stubbing at HTTP level
// — misses serialization, HTTP error handling, and real client behaviour.
@Mock
private PaymentClient paymentClient;
@Test
void testPayment() {
when(paymentClient.authorize(any())).thenReturn(new PaymentResponse("APPROVED"));
// This bypasses HTTP layer entirely — integration test value is lost.
// Use WireMock stubs to test the real HTTP client pipeline.
}
```
### Example 6: Anti-pattern: WireMock stubs registered globally in @BeforeAll
Title: Register stubs inside each test method to prevent inter-test contamination
Description: Registering WireMock stubs in `@BeforeAll` (or in the base class) means every test in the class shares the same stub responses. When one test needs a different response (e.g. a declined payment), its stub is added on top of the existing ones. WireMock matches by insertion order, which creates fragile, order-dependent tests. Register stubs inside each individual test method instead.
**Good example:**
```java
// ✅ Each test registers its own stub using a body file — fully isolated,
// order-independent, and response bodies are kept in wiremock/files/.
class PaymentServiceIT extends BaseIntegrationTest {
@Test
@DisplayName("Should confirm order when payment is approved")
void should_confirmOrder_when_paymentApproved() {
// Given — body loaded from wiremock/files/payment-service/authorize-approved-response.json
WIREMOCK.stubFor(post(urlEqualTo("/payments/authorize"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBodyFile("payment-service/authorize-approved-response.json")));
// When / Then ...
}
@Test
@DisplayName("Should reject order when payment is declined")
void should_rejectOrder_when_paymentDeclined() {
// Given — body loaded from wiremock/files/payment-service/authorize-declined-response.json
WIREMOCK.stubFor(post(urlEqualTo("/payments/authorize"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBodyFile("payment-service/authorize-declined-response.json")));
// When / Then ...
}
}
```
**Bad example:**
```java
// ❌ Problems: global stubs shared across all tests — stub state bleeds between tests,
// creating order-dependent failures that are difficult to diagnose.
class PaymentServiceIT extends BaseIntegrationTest {
@BeforeAll
static void globalStubs() {
WIREMOCK.stubFor(post(urlEqualTo("/payments/authorize"))
.willReturn(okJson("{\"status\":\"APPROVED\"}")));
}
@Test
void test_approved_payment() { /* accidentally depends on global stub */ }
@Test
void test_declined_payment() {
// ❌ This stub is added on top of the global one.
// WireMock prioritises the most recently registered stub,
// so the result depends on test execution order.
WIREMOCK.stubFor(post(urlEqualTo("/payments/authorize"))
.willReturn(okJson("{\"status\":\"DECLINED\"}")));
}
}
```
## Output Format
- **ASK** Step 1 questions one at a time, collecting REST topology before generating any code
- **SUMMARISE** the confirmed topology before proceeding to code generation (e.g. "You need: WireMock for payment-service")
- **GENERATE** `BaseIntegrationTest.java` tailored to the confirmed topology — include only the extensions that were explicitly selected
- **LIST** the required Maven dependencies immediately after generating `BaseIntegrationTest.java` using the dependency snippets from Example 4
- **GENERATE** WireMock JSON mapping files (one per confirmed external service) when REST integration was selected — place them under `src/test/resources/wiremock/mappings/{service-name}/`
- **EXPLAIN** the key design decisions in the generated code (System.setProperty() coordinate propagation, WireMockExtension lifecycle)
- **VALIDATE** that all generated code compiles by running `./mvnw test-compile` after the files are written
## Safeguards
- **BLOCKING SAFETY CHECK**: ALWAYS run `./mvnw compile` before generating integration-test scaffolding
- **CODE ANALYSIS FIRST**: ALWAYS inspect the class(es) provided in context for infrastructure import signals before asking topology questions — generate only what the component actually needs
- **NO UNNECESSARY CONTAINERS**: NEVER add `@Testcontainers` or Testcontainers Maven dependencies when only WireMock is needed — a REST-only component requires only `wiremock-standalone`
- **CRITICAL VALIDATION**: Run `./mvnw test-compile` after writing generated files to confirm they compile
- **MANDATORY**: Use `@BeforeAll` + `System.setProperty()` to propagate WireMock coordinates — never hardcode ports or connection strings in property files
- **WIREMOCK ISOLATION**: Register stubs inside each individual test method — shared stubs in `@BeforeAll` cause order-dependent failures
- **NO MOCK HTTP CLIENTS**: Never use Mockito to mock typed HTTP client wrappers in integration tests — use WireMock to test the real HTTP pipeline
- **DEPENDENCY SCOPE**: WireMock dependencies must have `scope=test` — never include them in production scopeRelated skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 195k | Updated | Claude CodeCodex | Verified | Install |