К основному содержанию
команда CX Codex

devkit.java.write-integration-tests — команда для Claude Code

Команда devkit.java.write-integration-tests для Claude Code генерирует интеграционные тесты для классов Spring Boot. Запускайте её для сервисов и репозиториев, передав путь к классу.

MIT ★ 372 обновлён 2026-09-10

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-java@developer-kit
Открыть на GitHub

Что делает devkit.java.write-integration-tests

Команда анализирует указанный Java-класс, определяет его слой и зависимости, а затем создаёт интеграционный тест с подходящими контейнерами Testcontainers. Для баз данных и кэша она выбирает PostgreSQL, Redis или MongoDB; для обмена сообщениями описаны варианты с RabbitMQ и Kafka.

В тестах применяются @ServiceConnection, AssertJ и @MockitoBean; команда также проверяет зависимости проекта для Maven или Gradle. Для Spring Boot 3.5+ указано подключение контейнеров через @ServiceConnection. В процессе задействуется агент developer-kit-java:spring-boot-unit-testing-expert, а при его недоступности предусмотрен переход к general-purpose с навыком spring-boot-test-patterns.

Какие задачи решает

  • создать интеграционный тест для класса Spring Boot
  • подобрать Testcontainers по зависимостям класса
  • проверить тестовые зависимости Maven или Gradle
  • покрыть сценарии сервиса или репозитория

Примеры запросов агенту

  • Создай интеграционный тест для src/main/java/com/example/UserService.java.
  • Напиши тест для репозитория src/main/java/com/example/UserRepository.java с контейнером для его базы данных.

Как установить devkit.java.write-integration-tests

1Через маркетплейс плагинов

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

2Вручную: положить файлы

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

Вызов — /devkit.java.write-integration-tests. Для всех проектов — ~/.claude/commands/

Вопросы о devkit.java.write-integration-tests

Как установить devkit.java.write-integration-tests в Claude Code?

Выполни команды по порядку: /plugin marketplace add giuseppe-trisciuoglio/developer-kit, затем /plugin install developer-kit-java@developer-kit.

Что делает devkit.java.write-integration-tests?

Анализирует класс Spring Boot и генерирует для него интеграционный тест, выбирая контейнеры Testcontainers по используемым зависимостям.

Какие контейнеры поддерживает devkit.java.write-integration-tests?

Для баз данных и кэша описаны PostgreSQL, Redis и MongoDB; для обмена сообщениями — RabbitMQ и Kafka.

Исходный текст

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

Похожие слэш-команды

Все слэш-команды по теме «Тесты и QA» →
create-spring-boot-java-project официальный github Скилл create-spring-boot-java-project разворачивает каркас приложения Spring Boot через start.spring.io с готовой конфигурацией базы данных, тестов и Docker. Запускается при запросе на генерацию нового сервиса на Java. CX Codex +1 9 516установок 522-frameworks-micronaut-testing-integration-tests Juan Antonio Breña Moral Скилл 522-frameworks-micronaut-testing-integration-tests помогает писать интеграционные тесты для Micronaut с Testcontainers и настраивать запуск через Maven. CX Codex +1 323установок 322-frameworks-spring-boot-testing-integration-tests Juan Antonio Breña Moral Скилл 322-frameworks-spring-boot-testing-integration-tests для Claude Code помогает писать и разбирать интеграционные тесты Spring Boot 4.0.x с Testcontainers, срезами персистентности и HTTP-проверками. CX Codex +1 388установок create-spring-boot-kotlin-project официальный github Скилл create-spring-boot-kotlin-project для GitHub Copilot, который разворачивает каркас Spring Boot-проекта на Kotlin. Скачивает шаблон со start.spring.io, добавляет зависимости и конфигурацию для Redis, PostgreSQL и MongoDB. CX Codex +1 8 700установок java-springboot-jpa-cursorrules-prompt-file PatrickJS Правило java-springboot-jpa-cursorrules-prompt-file для Cursor задаёт структуру Java-проектов на Spring Boot с JPA, DTO и разделением слоёв. Генерирует REST API по единой схеме. CX Codex +1 ★ 41 178звёзд репо java-architect VoltAgent Community Субагент java-architect проектирует архитектуру enterprise-приложений на Java 17+ и настраивает микросервисы на Spring Boot 3.x. Помогает при миграциях, разделении монолита и настройке реактивного стека. CX Codex 558установок

Из того же набора191

Весь набор →
aws-cloudformation-lambda Скилл aws-cloudformation-lambda для Claude Code содержит шаблоны CloudFormation для функций AWS Lambda: триггеры S3 и SQS, HTTP API Gateway, роли IAM и мониторинг CloudWatch. CX Codex +1 ★ 372звёзд репо devkit.github.create-pr Команда devkit.github.create-pr для Claude Code создаёт ветку, коммиты по Conventional Commits и pull request на GitHub по заголовку PR, целевой ветке и языку описания. CX Codex +1 ★ 372звёзд репо aws-drawio-architecture-diagrams Скилл aws-drawio-architecture-diagrams для Claude Code генерирует AWS-архитектуры в формате .drawio с официальными иконками aws4 по описанию инфраструктуры. CX Codex +1 ★ 372звёзд репо devkit.java.code-review Команда devkit.java.code-review проводит ревью Java-кода на Spring Boot: ищет уязвимости по OWASP, проверяет архитектуру, чинит проблемы производительности и инъекцию зависимостей перед мерджем. CX Codex +1 ★ 372звёзд репо devkit.ts.security-review Слэш-команда devkit.ts.security-review прогоняет безопасность TypeScript/Node.js приложения: npm audit, Semgrep, Snyk, потом ручная проверка по OWASP Top 10 и отчёт с приоритетами. CX Codex +1 ★ 372звёзд репо aws-cloudformation-ecs Скилл aws-cloudformation-ecs генерирует готовые шаблоны CloudFormation для кластеров Amazon ECS, задач Fargate и сервисов за балансировщиком нагрузки. CX Codex +1 ★ 372звёзд репо aws-cloudformation-auto-scaling Скилл aws-cloudformation-auto-scaling для Claude Code помогает собирать CloudFormation-шаблоны для Auto Scaling в EC2, ECS и Lambda. Описывает группы масштабирования, политики и хуки жизненного цикла. CX Codex +1 ★ 372звёзд репо wordpress-sage-theme Скилл wordpress-sage-theme подсказывает, как собрать тему WordPress на Sage: Blade-шаблоны, Vite или Bud, поля ACF. Заранее нужны PHP 8.0+, Node.js 18+ и Composer. CX Codex +1 ★ 372звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой