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

unit-test-controller-layer — скилл для Claude Code: как ставить

Генерирует модульные тесты для REST-контроллеров Spring через MockMvc и Mockito. Пригодится для быстрой проверки HTTP-статусов, валидации и JsonPath без запуска полного контекста.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill unit-test-controller-layer -a claude-code
Открыть на GitHub

Что делает unit-test-controller-layer

Скилл содержит шаблоны изолированного тестирования классов @RestController и @Controller с помощью MockMvcBuilders.standaloneSetup. Агент генерирует тесты для методов GET, POST, PUT, PATCH и DELETE, изолируя зависимости через @Mock и внедряя их в контроллер через @InjectMocks. В примерах описаны проверки статус-кодов, заголовков ответа, синтаксиса JsonPath и согласования типов контента через заголовки Accept и Content-Type.

В инструкциях разобран пошаговый процесс отладки: если тест падает, в цепочку вызовов добавляется .andDo(print()), чтобы сверить фактический ответ сервера с ожидаемым. Для компиляции и запуска сформированных тестов в Maven или Gradle потребуется зависимость spring-boot-starter-test.

Поскольку контроллер тестируется в изолированном режиме со всеми замокированными сервисами, этот скилл проверяет только HTTP-контракты и завершится ошибкой, если попытаться протестировать реальную бизнес-логику внутри сервисов.

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

  • сгенерировать изолированные тесты Spring REST контроллера через MockMvc standaloneSetup
  • проверить структуру тела ответа через JsonPath
  • протестировать валидацию входящих DTO с проверкой статуса 400
  • проверить сопоставление исключений сервиса с кодами 404 и 500

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

  • Напиши юнит-тест для UserController с MockMvc и проверкой всех статус-кодов
  • Добавь проверку валидации тела POST-запроса в UserControllerTest с выводом print() при падении
  • Проверь через MockMvc заголовки ответа и фильтрацию по query-параметрам в контроллере

Как установить unit-test-controller-layer

1Через Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill unit-test-controller-layer -a claude-code

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

~/.claude/skills/unit-test-controller-layer/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/unit-test-controller-layer/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о unit-test-controller-layer

Как установить unit-test-controller-layer в Claude Code?

Выполните команду npx skills add giuseppe-trisciuoglio/developer-kit --skill unit-test-controller-layer -a claude-code.

Что делает скилл unit-test-controller-layer?

Он предоставляет агенту готовые шаблоны для изолированного модульного тестирования Spring MVC контроллеров с помощью MockMvcBuilders.standaloneSetup, Mockito и JsonPath.

Какие зависимости нужны в проекте для сгенерированных тестов?

В конфигурационном файле сборщика Maven или Gradle должна быть объявлена зависимость org.springframework.boot:spring-boot-starter-test в тестовой области видимости.

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

SKILL.md · MIT
---
name: unit-test-controller-layer
description: Provides patterns for unit testing REST controllers using MockMvc and @WebMvcTest. Generates controller tests that validates request/response mapping, validation, exception handling, and HTTP status codes. Use when testing web layer endpoints in isolation for API endpoint testing, Spring MVC tests, mock HTTP requests, or controller layer unit tests.
allowed-tools: Read, Write, Bash, Glob, Grep
---

# Unit Testing REST Controllers with MockMvc

## Overview

Provides patterns for unit testing `@RestController` and `@Controller` classes using MockMvc. Covers request/response handling, HTTP status codes, request parameter binding, validation, content negotiation, response headers, and exception handling with mocked service dependencies.

## When to Use

Use for: controller tests, API endpoint testing, Spring MVC tests, mock HTTP requests, unit testing web layer endpoints, verifying REST controllers in isolation.

## Instructions

1. **Setup standalone MockMvc**: `MockMvcBuilders.standaloneSetup(controller)` for isolated testing
2. **Mock service dependencies**: Use `@Mock` for all services, `@InjectMocks` for the controller
3. **Test HTTP methods**: GET, POST, PUT, PATCH, DELETE with correct status codes
4. **Validate responses**: JsonPath assertions for JSON, content matchers for body
5. **Test validation**: Send invalid input, verify 400 status with error details
6. **Test errors**: Verify 404, 400, 401, 403, 500 for appropriate conditions
7. **Validate headers**: Both request (Authorization) and response headers
8. **Test content negotiation**: Different Accept and Content-Type headers

### Validation Workflow

```
Run test → If fails: add .andDo(print()) → Check actual vs expected → Fix assertion
```

## Examples

### Maven / Gradle Dependencies

```xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
```

### Basic Pattern: GET Endpoint

```java
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@ExtendWith(MockitoExtension.class)
class UserControllerTest {

  @Mock
  private UserService userService;

  @InjectMocks
  private UserController userController;

  private MockMvc mockMvc;

  @BeforeEach
  void setUp() {
    mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
  }

  @Test
  void shouldReturnAllUsers() throws Exception {
    List<UserDto> users = List.of(new UserDto(1L, "Alice"), new UserDto(2L, "Bob"));
    when(userService.getAllUsers()).thenReturn(users);

    mockMvc.perform(get("/api/users"))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$[0].id").value(1))
      .andExpect(jsonPath("$[0].name").value("Alice"));

    verify(userService, times(1)).getAllUsers();
  }

  @Test
  void shouldReturn404WhenUserNotFound() throws Exception {
    when(userService.getUserById(999L))
      .thenThrow(new UserNotFoundException("User not found"));

    mockMvc.perform(get("/api/users/999"))
      .andExpect(status().isNotFound());

    verify(userService).getUserById(999L);
  }
}
```

### POST: Create Resource

```java
@Test
void shouldCreateUserAndReturn201() throws Exception {
  UserDto createdUser = new UserDto(1L, "Alice", "[email protected]");
  when(userService.createUser(any())).thenReturn(createdUser);

  mockMvc.perform(post("/api/users")
      .contentType("application/json")
      .content("{\"name\":\"Alice\",\"email\":\"[email protected]\"}"))
    .andExpect(status().isCreated())
    .andExpect(jsonPath("$.id").value(1))
    .andExpect(jsonPath("$.name").value("Alice"));

  verify(userService).createUser(any(UserCreateRequest.class));
}
```

### PUT: Update Resource

```java
@Test
void shouldUpdateUserAndReturn200() throws Exception {
  UserDto updatedUser = new UserDto(1L, "Updated");
  when(userService.updateUser(eq(1L), any())).thenReturn(updatedUser);

  mockMvc.perform(put("/api/users/1")
      .contentType("application/json")
      .content("{\"name\":\"Updated\"}"))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.name").value("Updated"));

  verify(userService).updateUser(eq(1L), any());
}
```

### DELETE: Remove Resource

```java
@Test
void shouldDeleteUserAndReturn204() throws Exception {
  doNothing().when(userService).deleteUser(1L);

  mockMvc.perform(delete("/api/users/1"))
    .andExpect(status().isNoContent());

  verify(userService).deleteUser(1L);
}
```

### Query Parameters

```java
@Test
void shouldFilterUsersByName() throws Exception {
  when(userService.searchUsers("Alice")).thenReturn(List.of(new UserDto(1L, "Alice")));

  mockMvc.perform(get("/api/users/search").param("name", "Alice"))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$[0].name").value("Alice"));

  verify(userService).searchUsers("Alice");
}
```

### Path Variables

```java
@Test
void shouldGetUserByIdFromPath() throws Exception {
  when(userService.getUserById(123L)).thenReturn(new UserDto(123L, "Alice"));

  mockMvc.perform(get("/api/users/{id}", 123L))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.id").value(123));
}
```

### Validation Errors (400)

```java
@Test
void shouldReturn400WhenRequestBodyInvalid() throws Exception {
  mockMvc.perform(post("/api/users")
      .contentType("application/json")
      .content("{\"name\":\"\"}"))
    .andExpect(status().isBadRequest())
    .andExpect(jsonPath("$.errors").isArray());
}
```

### Response Headers

```java
@Test
void shouldReturnCustomHeaders() throws Exception {
  when(userService.getAllUsers()).thenReturn(List.of());

  mockMvc.perform(get("/api/users"))
    .andExpect(status().isOk())
    .andExpect(header().exists("X-Total-Count"))
    .andExpect(header().string("X-Total-Count", "0"));
}
```

### Authorization Header

```java
@Test
void shouldRequireAuthorizationHeader() throws Exception {
  mockMvc.perform(get("/api/users"))
    .andExpect(status().isUnauthorized());

  mockMvc.perform(get("/api/users").header("Authorization", "Bearer token"))
    .andExpect(status().isOk());
}
```

### Content Negotiation

```java
@Test
void shouldReturnJsonWhenAcceptHeaderIsJson() throws Exception {
  when(userService.getUserById(1L)).thenReturn(new UserDto(1L, "Alice"));

  mockMvc.perform(get("/api/users/1").accept("application/json"))
    .andExpect(status().isOk())
    .andExpect(content().contentType("application/json"));
}
```

## Best Practices

- Use `standaloneSetup()` for isolated controller testing
- Mock service layer — controllers handle HTTP, services handle business logic
- Verify mock interactions: `verify(service).method(args)`
- Test happy path AND error scenarios (404, 400, 500)
- Use `jsonPath()` for fluent JSON assertions
- One focused assertion per test method

## Constraints and Warnings

- Controller tests verify HTTP handling only — not full request flow
- `standaloneSetup()` may not support `@Validated` without full context
- JsonPath requires valid JSON in response body
- `@PreAuthorize`/`@Secured` need additional setup — consider separate security tests
- File uploads require `MockMultipartFile`

## References

- [Spring MockMvc Documentation](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/MockMvc.html)
- [Spring Testing Best Practices](https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing)

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

Похожие скиллы

Всё по теме «Тесты и QA» →
321-frameworks-spring-boot-testing-unit-tests Juan Antonio Breña Moral Скилл ведёт агента по юнит-тестам Spring Boot: Mockito без поднятия контекста, срезы для контроллеров, параметризованные тесты. Пригодится, когда в проекте расплодились @SpringBootTest. CX Codex +1 387установок 131-java-testing-unit-testing Juan Antonio Breña Moral Скилл помогает писать и рефакторить модульные тесты на Java по стандартам JUnit 5, AssertJ и Mockito. Он находит антипаттерны вроде общего состояния и проверяет граничные условия. CX Codex +1 449установок Python Unit Test Generator — Comprehensive, Coverage-Mapped & Production-Ready sivasaiyadav8143 Промпт превращает кусок Python-кода в готовый набор юнит-тестов на pytest с картой покрытия и моками внешних зависимостей. GP ChatGPT ★ 174 597звёзд репо spring-boot-engineer https://github.com/Jeffallan Разворачивает архитектуру Spring Boot 3.x, контроллеры, репозитории Spring Data JPA и правила Spring Security 6. Пригодится при сборке REST API, реактивных сервисов и микросервисов на Java. CX Codex +1 8 400установок spring-boot Mindrally Скилл задаёт агенту стиль кода на Spring Boot: REST-контроллеры, тесты, безопасность, сборка и деплой. Пригодится, когда проект на Java и хочется единообразия. CX Codex +1 832установок spring-framework Mindrally Скилл задаёт агенту правила разработки на Spring Framework и Spring Boot: структура слоёв, внедрение зависимостей, тесты, REST. CX Codex +1 731установок

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

typescript-security-review Проверяет код TypeScript и Node.js на уязвимости OWASP, утечки секретов и ошибки в настройке JWT или CORS. Пригодится перед релизом или при аудите авторизации в Express, NestJS и Next.js. CX Codex +1 3 900установок prompt-engineering Скилл помогает писать, отлаживать и проверять промпты для LLM. Пригодится для few-shot-примеров, системных инструкций и шаблонов. CX Codex +1 3 900установок spring-boot-saga-pattern Скилл для распределённых транзакций в микросервисах на Spring Boot: хореография и оркестрация, компенсирующие операции, Kafka, RabbitMQ, Axon. CX Codex +1 3 800установок unit-test-json-serialization Скилл подсказывает, как писать юнит-тесты сериализации и десериализации JSON на Jackson и @JsonTest в Spring Boot. CX Codex +1 3 800установок unit-test-parameterized Скилл для параметризованных тестов на JUnit 5: один метод гоняет много входных значений. Пригодится, когда надо покрыть граничные случаи без копипасты. CX Codex +1 3 800установок nextjs-authentication Скилл даёт готовые шаблоны аутентификации для Next.js 15+ App Router на Auth.js 5: провайдеры, защита маршрутов, сессии и роли. CX Codex +1 3 800установок spring-boot-dependency-injection Скилл внедряет паттерны внедрения зависимостей через конструктор в Spring Boot. Он помогает избавиться от field injection и настроить выбор бинов через @Primary и @Qualifier. CX Codex +1 3 800установок nextjs-code-review Проверяет код Next.js перед слиянием изменений: компоненты, серверные действия, кэш и маршруты. Пригодится после новой функции или миграции. CX Codex +1 3 800установок

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

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