Skip to main content
command CX Codex

devkit.java.write-integration-tests — Claude Code command

devkit.java.write-integration-tests is a Claude Code command that generates integration tests for Spring Boot classes. Give it a class path to test a service or repository.

MIT ★ 372 updated 2026-09-10

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-java@developer-kit
Open on GitHub

What devkit.java.write-integration-tests does

The command reads the target Java class, identifies its layer and dependencies, then generates an integration test with matching Testcontainers. It covers PostgreSQL, Redis and MongoDB, with RabbitMQ and Kafka listed for messaging workloads.

Generated tests use @ServiceConnection, AssertJ and @MockitoBean; the command also checks Maven or Gradle test dependencies. The instructions specify @ServiceConnection for Spring Boot 3.5+. The task uses developer-kit-java:spring-boot-unit-testing-expert; if that agent is unavailable, it gives a fallback using general-purpose and the spring-boot-test-patterns skill.

What it helps with

  • generate an integration test for a Spring Boot class
  • choose Testcontainers based on class dependencies
  • check Maven or Gradle test dependencies
  • cover service or repository scenarios

Example prompts for the agent

  • Generate an integration test for src/main/java/com/example/UserService.java.
  • Write an integration test for src/main/java/com/example/UserRepository.java using a container for its database.

How to install devkit.java.write-integration-tests

1Plugin marketplace

/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-java@developer-kit

2Manually: put the files in place

.claude/commands/devkit.java.write-integration-tests.md

Call it with /devkit.java.write-integration-tests. For all projects use ~/.claude/commands/

Questions about devkit.java.write-integration-tests

How do I install devkit.java.write-integration-tests in Claude Code?

Run these commands in order: /plugin marketplace add giuseppe-trisciuoglio/developer-kit, then /plugin install developer-kit-java@developer-kit.

What does devkit.java.write-integration-tests do?

It analyzes a Spring Boot class and creates an integration test, selecting Testcontainers according to the class's dependencies.

Which containers does devkit.java.write-integration-tests support?

The instructions cover PostgreSQL, Redis and MongoDB for data or caching, plus RabbitMQ and Kafka for messaging.

Source text

devkit.java.write-integration-tests.md · MIT
---
allowed-tools: Read, Write, Bash, Grep, Glob
argument-hint: "[class-path]"
description: Generates comprehensive integration tests for Spring Boot classes using Testcontainers (PostgreSQL, Redis, MongoDB) with `@ServiceConnection` pattern. Use when writing integration tests for service or repository classes.
model: inherit
---

# Write Integration Tests for Spring Boot

## Overview

Generates comprehensive integration tests for Spring Boot classes using Testcontainers (PostgreSQL, Redis, MongoDB) with
`@ServiceConnection` pattern. Use when writing integration tests for service or repository classes.

You are tasked with generating a complete integration test for the Java class specified in `$1`.

### Usage

When analyzing the target class, Claude will automatically reference these skills to:

- Determine the appropriate test strategy based on layer (Controller/Service/Repository)
- Select the correct Testcontainers based on dependencies
- Apply framework-specific testing patterns
- Generate comprehensive test scenarios covering all edge cases
- Use `@MockitoBean` for mocking dependencies (replaces deprecated `@MockBean`)

## Arguments

| Argument     | Description                              |
|--------------|------------------------------------------|
| `$ARGUMENTS` | Combined arguments passed to the command |

## Execution Instructions

**Agent Selection**: To execute this task, use the following agent with fallback:

- Primary: `developer-kit-java:spring-boot-unit-testing-expert`
- If not available: Use `developer-kit-java:spring-boot-unit-testing-expert` or fallback to `general-purpose` agent with
  `spring-boot-test-patterns` skill

## Process

### 1. Analyze Target Class

- Read the class file from `$1`
- Identify the layer (Controller, Service, Repository)
- Detect dependencies (Database, Cache, Message Queue, etc.)
- Identify external integrations

### 2. Determine Required Testcontainers

Based on dependencies, include:

- **PostgreSQL**: For JPA repositories or database operations
- **Redis**: For caching or session management
- **MongoDB**: For NoSQL operations
- **RabbitMQ/Kafka**: For messaging operations
- **Additional containers**: Based on specific dependencies

### 3. Generate Integration Test

Follow these patterns from the spring-boot-test-patterns skill:

#### Test Structure

```java
@SpringBootTest
@Testcontainers class

<ClassName> IntegrationTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(
            DockerImageName.parse("postgres:16-alpine"))
            .withDatabaseName("testdb")
            .withUsername("test")
            .withPassword("test");

    @Container
    @ServiceConnection
    static GenericContainer<?> redis = new GenericContainer<>(
            DockerImageName.parse("redis:7-alpine"))
            .withExposedPorts(6379);

    @Autowired
    private <TargetClass > targetClass;

    @Test
    void shouldPerformIntegrationScenario () {
        // Test implementation
    }
}
```

#### Key Requirements

1. **Use `@ServiceConnection`** for Spring Boot 3.5+ automatic wiring
2. **Static containers** for reuse across test methods
3. **Minimal context loading** - only load what's needed
4. **Real dependencies** via Testcontainers
5. **Complete scenarios** - test full workflows
6. **Proper assertions** - use AssertJ for fluent assertions
7. **Use `@MockitoBean`** (not deprecated `@MockBean`) from `org.springframework.test.context.bean.override.mockito`

#### Container Selection Guidelines

- **`@Repository`/`@DataJpaTest`**: PostgreSQL/MySQL container
- **`@Service` with caching**: Redis container
- **`@RestController`**: MockMvc + required backend containers
- **Message consumers/producers**: RabbitMQ/Kafka container
- **MongoDB repositories**: MongoDB container

### 4. Dependencies Check

Verify and add required dependencies:

**Maven:**

```xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.19.0</version>
// Use latest stable version
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.19.0</version>
// Use latest stable version
<scope>test</scope>
</dependency>
```

**Gradle:**

```kotlin
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.testcontainers:junit-jupiter:1.19.0")
testImplementation("org.testcontainers:postgresql:1.19.0")
```

### 5. Test Coverage

Generate tests covering:

- ✅ Happy path scenarios
- ✅ Edge cases and boundary conditions
- ✅ Error handling and validation
- ✅ Transaction rollback scenarios
- ✅ Concurrent access patterns (if applicable)

### 6. Performance Optimization

- Use static containers for JVM-level reuse
- Avoid `@DirtiesContext` unless absolutely necessary
- Group tests with similar configuration
- Target: < 500ms per integration test

## Example Patterns

### Controller Integration Test

```java

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class UserControllerIntegrationTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(
            DockerImageName.parse("postgres:16-alpine"));

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void shouldCreateAndRetrieveUser() {
        UserRequest request = new UserRequest("[email protected]", "John Doe");

        ResponseEntity<UserResponse> createResponse = restTemplate
                .postForEntity("/api/users", request, UserResponse.class);

        assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(createResponse.getBody()).isNotNull();

        Long userId = createResponse.getBody().id();

        ResponseEntity<UserResponse> getResponse = restTemplate
                .getForEntity("/api/users/" + userId, UserResponse.class);

        assertThat(getResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(getResponse.getBody().email()).isEqualTo("[email protected]");
    }
}
```

### Controller with Mocked Service

```java
import org.springframework.test.context.bean.override.mockito.MockitoBean;

@WebMvcTest(UserController.class)
@Testcontainers
class UserControllerMockTest {

    @Autowired
    private MockMvc mockMvc;

    @MockitoBean  // Use @MockitoBean instead of deprecated @MockBean
    private UserService userService;

    @Test
    void shouldReturnUserWhenExists() throws Exception {
        User user = new User(1L, "[email protected]", "John Doe");
        when(userService.findById(1L)).thenReturn(Optional.of(user));

        mockMvc.perform(get("/api/users/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.email").value("[email protected]"));
    }
}
```

### Service with Cache Integration Test

```java

@SpringBootTest
@Testcontainers
class UserServiceIntegrationTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(
            DockerImageName.parse("postgres:16-alpine"));

    @Container
    @ServiceConnection
    static GenericContainer<?> redis = new GenericContainer<>(
            DockerImageName.parse("redis:7-alpine"))
            .withExposedPorts(6379);

    @Autowired
    private UserService userService;

    @Autowired
    private CacheManager cacheManager;

    @Test
    void shouldCacheUserAfterFirstRetrieval() {
        User user = userService.createUser("[email protected]", "Test User");

        // First call - hits database
        User firstCall = userService.findById(user.getId());
        assertThat(firstCall).isNotNull();

        // Verify cached
        Cache userCache = cacheManager.getCache("users");
        assertThat(userCache.get(user.getId())).isNotNull();

        // Second call - hits cache
        User secondCall = userService.findById(user.getId());
        assertThat(secondCall).isEqualTo(firstCall);
    }
}
```

### Repository Integration Test

```java

@DataJpaTest
@Testcontainers
class UserRepositoryIntegrationTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(
            DockerImageName.parse("postgres:16-alpine"));

    @Autowired
    private UserRepository userRepository;

    @Test
    void shouldFindUsersByEmailDomain() {
        userRepository.save(new User("[email protected]", "John"));
        userRepository.save(new User("[email protected]", "Jane"));
        userRepository.save(new User("[email protected]", "Bob"));

        List<User> exampleUsers = userRepository.findByEmailEndingWith("@example.com");

        assertThat(exampleUsers).hasSize(2);
        assertThat(exampleUsers)
                .extracting(User::getEmail)
                .containsExactlyInAnyOrder("[email protected]", "[email protected]");
    }
}
```

## Output

1. Create test file in `src/test/java` matching package structure
2. Name: `<ClassName>IntegrationTest.java`
3. Include all necessary imports
4. Add appropriate Testcontainers based on dependencies
5. Implement comprehensive test scenarios
6. Add comments explaining complex scenarios

## Verification

After generating the test:

1. Verify all imports are correct
2. Check Testcontainer versions match project dependencies
3. Ensure `@ServiceConnection` is used (Spring Boot 3.5+)
4. Validate test completeness against requirements
5. Run the test: `./mvnw test -Dtest=<ClassName>IntegrationTest`

## Best Practices

- ✅ Use static containers for performance
- ✅ Prefer `@ServiceConnection` over `@DynamicPropertySource`
- ✅ Use `@MockitoBean` instead of deprecated `@MockBean` (from `org.springframework.test.context.bean.override.mockito`)
- ✅ Test complete workflows, not isolated methods
- ✅ Use meaningful test method names describing scenarios
- ✅ Add `@Transactional` on test methods for automatic rollback
- ✅ Use AssertJ for fluent, readable assertions
- ❌ Avoid `@DirtiesContext` unless absolutely necessary
- ❌ Don't mix unit test patterns in integration tests
- ❌ Don't hardcode ports or URLs

## Available Skills Reference

This command leverages the following skills available in the repository:

### Testing Skills

- **spring-boot-test-patterns** - Core integration testing patterns with Testcontainers and @ServiceConnection
- **unit-test-controller-layer** - REST controller testing with MockMvc
- **unit-test-service-layer** - Service layer testing with Mockito
- **unit-test-caching** - Testing cache behaviors with Redis
- **unit-test-json-serialization** - Testing JSON serialization/deserialization
- **unit-test-exception-handler** - Testing `@ControllerAdvice` exception handlers
- **unit-test-wiremock-rest-api** - Testing external REST APIs with WireMock
- **unit-test-scheduled-async** - Testing `@Scheduled` and `@Async` methods
- **unit-test-security-authorization** - Testing Spring Security and authorization

### Spring Boot Skills

- **spring-boot-rest-api-standards** - REST API design patterns to test
- **spring-boot-crud-patterns** - CRUD operation patterns to test
- **spring-boot-cache** - Caching strategies with Spring Cache
- **spring-boot-dependency-injection** - Constructor injection patterns
- **spring-boot-event-driven-patterns** - Event-driven architecture testing
- **spring-data-jpa** - JPA repository patterns

### Important Notes

- **`@MockitoBean` vs `@MockBean`**: Spring Framework 6.2+ introduces `@MockitoBean` from
  `org.springframework.test.context.bean.override.mockito` package. The old `@MockBean` from
  `org.springframework.boot.test.mock.mockito` is deprecated.
- **Package import**: Always use `import org.springframework.test.context.bean.override.mockito.MockitoBean;`
- **Reference
  **: [Spring Framework MockitoBean Documentation](https://docs.spring.io/spring-framework/reference/6.2/testing/annotations/integration-spring/annotation-mockitobean.html)

---

**Target class:** `$ARGUMENTS`

Analyze the class and generate a comprehensive integration test following the patterns above.

## Examples

```bash
/devkit.java.write-integration-tests example-input
```

© Giuseppe Trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar slash commands

All slash commands for Testing and QA →
create-spring-boot-java-project official github create-spring-boot-java-project scaffolds a Spring Boot Java application via start.spring.io with preset defaults for databases, testing, and Docker. Triggers when asked to bootstrap a new Java service. CX Codex +1 9,516installs 522-frameworks-micronaut-testing-integration-tests Juan Antonio Breña Moral 522-frameworks-micronaut-testing-integration-tests guides writing Micronaut integration tests using Testcontainers and Maven test configurations. CX Codex +1 323installs 322-frameworks-spring-boot-testing-integration-tests Juan Antonio Breña Moral 322-frameworks-spring-boot-testing-integration-tests is a Claude Code skill for writing and reviewing Spring Boot 4.0.x integration tests with Testcontainers, persistence slices, and HTTP assertions. CX Codex +1 388installs create-spring-boot-kotlin-project official github create-spring-boot-kotlin-project — a GitHub Copilot skill that scaffolds a Spring Boot project in Kotlin. It pulls a template from start.spring.io, wires up Redis, PostgreSQL and MongoDB, then runs the test suite. CX Codex +1 8,700installs java-springboot-jpa-cursorrules-prompt-file PatrickJS The java-springboot-jpa-cursorrules-prompt-file rule guides Cursor when building Java Spring Boot projects with JPA, DTOs, and layered APIs. Use it when generated code should follow a fixed structure. CX Codex +1 ★ 41,178repo stars java-architect VoltAgent Community java-architect designs enterprise Java 17+ architectures and configures Spring Boot 3.x microservices. Helps migrate services, isolate domain logic, and adopt reactive pipelines. CX Codex 558installs

From the same set191

The whole set →
aws-cloudformation-lambda aws-cloudformation-lambda is a Claude Code skill with CloudFormation templates for AWS Lambda functions, S3 and SQS triggers, HTTP API Gateway, and CLI workflows. CX Codex +1 ★ 372repo stars devkit.github.create-pr devkit.github.create-pr — a Claude Code command that creates a branch, commits changes following Conventional Commits, and opens a GitHub pull request with a structured description. CX Codex +1 ★ 372repo stars aws-drawio-architecture-diagrams aws-drawio-architecture-diagrams — a Claude Code skill that produces AWS architecture .drawio files using the official aws4 icon library. Describe your infrastructure and the agent writes valid XML ready to open in diagrams.net. CX Codex +1 ★ 372repo stars devkit.java.code-review devkit.java.code-review reviews Java enterprise code in Spring Boot projects. Checks security against OWASP Top 10, inspects architecture and catches performance bottlenecks. CX Codex +1 ★ 372repo stars devkit.ts.security-review devkit.ts.security-review runs a security pass on a TypeScript/Node.js app: npm audit, Semgrep, Snyk, then a manual OWASP Top 10 review and a report sorted by risk. CX Codex +1 ★ 372repo stars aws-cloudformation-ecs aws-cloudformation-ecs generates AWS CloudFormation templates for ECS clusters, Fargate task definitions, and services behind load balancers. CX Codex +1 ★ 372repo stars aws-cloudformation-auto-scaling aws-cloudformation-auto-scaling is a Claude Code skill that builds CloudFormation templates for Auto Scaling across EC2, ECS, and Lambda, including scaling groups, policies, and lifecycle hooks. CX Codex +1 ★ 372repo stars wordpress-sage-theme wordpress-sage-theme walks Claude through building a WordPress theme on Sage: Blade views, Bud or Vite builds, ACF fields. PHP 8.0+, Node.js 18+ and Composer are needed first. CX Codex +1 ★ 372repo stars

Project sponsors

Companies that keep this analytics open