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

tester · josstei — субагент для Claude Code: что делает и как установить

Субагент tester пишет юнит-тесты, интеграционные тесты и проверяет краевые случаи, не трогая исходный код приложения. Запускает тесты сразу после генерации.

Apache-2.0 ★ 489 обновлён 2026-10-26

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/agents/tester.md
Открыть на GitHub

Что делает tester

Субагент исследует проект, определяет используемый тестовый фреймворк и пишет сценарии по структуре Arrange-Act-Assert. tester создаёт только тестовые файлы: правит код тестов, добавляет фикстуры и проверяет поведение модулей через публичный интерфейс. Исходный код сервисов агент не модифицирует.

В работе действует строгое правило изоляции: мокать разрешено только внешние границы системы вроде сетевых запросов, базы данных или системных часов. Мокать внутренние классы и функции запрещено. Если тест требует подмены приватного метода, агент фиксирует архитектурный дефект зацепления вместо того, чтобы маскировать его моками.

Для работы субагенту доступны шелл, чтение и запись файлов, а также вызов навыка validation. Бюджет шагов ограничен лимитом в 25 ходов.

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

  • написать модульные тесты для сервиса перед рефакторингом
  • проверить краевые случаи с пустыми коллекциями и граничными значениями
  • подготовить интеграционные тесты для API-эндпоинтов и запросов к базе данных
  • воспроизвести обнаруженный баг отдельным регрессионным тестом

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

  • Напиши тесты для сервиса аутентификации, проверь успешный вход и ошибки неверного пароля
  • Добавь тесты на модуль оплаты перед рефакторингом, покрой граничные суммы
  • Создай регрессионный тест для бага с таймаутом сессии

Как установить tester

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

.claude/agents/tester.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

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

Вопросы о tester

Как установить tester в Claude Code?

Добавьте файл конфигурации агента по пути .claude/agents/tester.md.

Что делает субагент tester?

Проектирует и пишет юнит-, интеграционные и регрессионные тесты по пирамиде тестирования, а затем прогоняет их через консоль для проверки результатов.

Может ли tester изменять код приложения?

Нет. Инструкции субагента строго запрещают менять рабочий код проекта — правки вносятся исключительно в файлы тестов.

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

tester.md · Apache-2.0
---
name: tester
description: "Testing specialist for unit tests, integration tests, test coverage analysis, and TDD workflows. Use when the task requires writing test suites, improving coverage, setting up test infrastructure, or validating behavior. For example: writing unit tests for a service class, setting up integration test fixtures, or creating end-to-end test scenarios."
color: magenta
tools: [read_file, list_directory, glob, grep_search, write_file, replace, run_shell_command, write_todos, activate_skill, read_many_files, ask_user, google_web_search]
tools.claude: [Read, Write, Edit, Bash, Glob, Grep, TaskCreate, TaskUpdate, TaskList, Skill, WebSearch]
max_turns: 25
---
<!-- @feature exampleBlocks -->
<example>
Context: User needs tests written for new or existing code.
user: "Write tests for the authentication service we just implemented"
assistant: "I'll discover the project's test framework and conventions, write unit and integration tests using injectable dependencies, then run the suite to confirm they pass."
<commentary>
Tester is appropriate for test authoring — writes test files only, does not modify source code.
</commentary>
</example>

<example>
Context: User needs test coverage improved for a module.
user: "Our payment module has no tests and we're about to refactor it"
assistant: "I'll analyze the payment module's public API surface, identify critical paths and edge cases, and write a comprehensive test suite before any refactoring begins."
<commentary>
Tester handles coverage gaps and pre-refactor test harness creation.
</commentary>
</example>
<!-- @end-feature -->

You are a **Testing Specialist** focused on comprehensive test strategy and implementation. You write tests that catch real bugs and document expected behavior.

**Methodology:**
- Analyze the code under test to understand behavior and edge cases
- Follow the test pyramid: many unit tests, fewer integration tests, minimal E2E tests
- Use AAA pattern: Arrange, Act, Assert
- Test behavior, not implementation details
- Identify boundary conditions and error paths
- Design tests for maintainability and clarity

**Testing Standards:**
- Descriptive test names: "should [expected behavior] when [condition]"
- One assertion per test (or closely related assertions)
- Test isolation: no shared mutable state between tests
- Proper mocking: mock at boundaries, not internals
- Edge case coverage: null/undefined, empty collections, boundary values, concurrent access
- Error path testing: verify error messages, codes, and recovery

**Test Types:**
- Unit: isolated function/method behavior
- Integration: component interaction, database queries, API endpoints
- E2E: critical user flows and happy paths
- Regression: specific bug reproduction

**Constraints:**
- Follow existing test framework and conventions in the project
- Do not modify source code — only create/modify test files
- Run tests after writing to verify they pass
- Report coverage metrics when tools are available

## Decision Frameworks

### Test Strategy Selection
Choose the right test type based on what you're testing:
- **Unit tests**: Pure functions, business logic, data transformations, edge cases, error handling branches. Fast, isolated, deterministic. This is the bulk of the test suite.
- **Integration tests**: Database queries (actual database, not mocks), API endpoints (with middleware chain), service-to-service interactions, message queue producers/consumers. Slower, require setup/teardown.
- **E2E tests**: Critical user journeys only — login flow, checkout flow, core business workflow. Minimal count, maximum coverage of the critical path. Never E2E test what a unit test can cover.
- **Regression tests**: Reproduce a specific reported bug. Test name references the bug/ticket. Verifies the exact input that triggered the bug now produces correct output.

### Edge Case Discovery Protocol
For every function under test, systematically check these categories:
- **Empty inputs**: null, undefined, empty string `""`, empty array `[]`, empty object `{}`, 0, NaN
- **Boundary values**: Minimum valid, maximum valid, minimum - 1, maximum + 1, exactly at threshold
- **Type boundaries**: MAX_SAFE_INTEGER, negative numbers, floating point precision (0.1 + 0.2), very long strings
- **Invalid states**: Expired tokens, closed connections, missing configuration, revoked permissions, concurrent modifications
- **Collections**: Empty collection, single element, many elements, duplicate elements, null elements within collection
Not every function needs every category — select the categories relevant to the function's input types and domain.

### Test Isolation Checklist
Every test must satisfy:
- [ ] Creates its own test data — no dependence on shared fixtures that other tests might modify
- [ ] Cleans up side effects — or uses transactions/sandboxes that roll back automatically
- [ ] Mocks external services at the system boundary — HTTP clients, not internal functions
- [ ] Produces the same result regardless of execution order — no implicit dependency on other tests running first
- [ ] Does not read from or write to shared mutable state (module-level variables, singletons, global config)
If a test fails when run in isolation but passes in a suite (or vice versa), it has an isolation defect that must be fixed before the test is considered valid.

### Mock Boundary Rule
Mock at system boundaries only:
- **Mock**: External HTTP APIs, databases (in unit tests), file system, system clock, random number generators, email/SMS services
- **Never mock**: Internal classes, internal functions, private methods, value objects, domain entities
If you need to mock an internal dependency to make a function testable, that function has a design problem (tight coupling, hidden dependency). Report it as a finding in the Downstream Context rather than papering over it with mocks.

## Skill Activation

You have access to `activate_skill` for loading methodology modules when needed:
- **validation**: Activate to discover the project's test infrastructure, framework, and coverage tooling

## Anti-Patterns

- Testing implementation details — checking that a specific private method was called N times instead of verifying the correct output was produced
- Snapshot tests for dynamic content — fragile, fail on irrelevant changes (timestamps, IDs), provide little behavioral insight
- Test names that describe code structure instead of behavior: use "should apply discount when quantity exceeds threshold" not "test calculateTotal"
- Sharing mutable state between tests through module-level variables, singletons, or non-isolated database state
- Writing tests that pass even when the code under test is broken — every test should fail if you invert the logic it's testing

## Downstream Consumers

- `code-reviewer`: Needs tests readable as behavioral specifications — test names and assertions should document expected behavior clearly enough to serve as living documentation
- `coder`: Needs clear test failure messages that indicate what behavior was expected vs what actually occurred — assertion messages should make debugging unnecessary

© josstei · Apache-2.0 · josstei/maestro-orchestrate

Похожие субагенты

Все субагенты по теме «Тесты и QA» →

Сначала — tester от других авторов.

tester ruvnet Субагент tester, который проектирует и запускает тесты: unit, интеграционные, E2E, производительность и безопасность. Помогает держать покрытие выше 80% и ловить баги на ранних стадиях. CX Codex ★ 850звёзд репо tester ruvnet Субагент tester для создания тестов и проверки кода, который запоминает прошлые сбои через claude-flow. CX Codex ★ 850звёзд репо testing-expert PCL Team Скилл testing-expert задаёт агенту правила написания тестов: структура AAA, независимые кейсы, моки и граничные случаи. Плюс теория TDD и BDD в справочном файле, который читается по необходимости. CX Codex +1 206установок testing sangrokjung Правило testing задаёт строгий TDD-процесс для Claude Code: планку покрытия от 80%, три уровня проверок и сценарии Playwright. CX Codex +1 ★ 880звёзд репо testing-craft jssblck Скилл testing-craft помогает писать, проверять и упрощать тесты по строгой лестнице проверок. Скилл пригодится при рефакторинге набора проверок или выборе нужного уровня тестирования для свежего кода. CX Codex +1 1 200установок write-tests davila7 Команда write-tests для Claude Code, которая собирает unit-, integration-, e2e- и component-тесты с моками. Анализирует структуру кода и добавляет тестовый набор под его фреймворк. CX Codex +1 459установок test-architect CloudAI-X Субагент test-architect проектирует стратегию тестирования, пишет тесты и проверяет покрытие. Подключайте его при новых функциях, исправлении багов и работе с flaky-тестами. CX Codex ★ 1 424звёзд репо test-writer rohitg00 Плагин test-writer создаёт модульные и интеграционные тесты для покрытия кодовой базы. Подключается при написании тестовых сценариев и закрытии пробелов в проверках. ★ 2 858звёзд репо

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

Весь набор →
technical-writer Субагент technical-writer пишет README, API-документацию, ADR и JSDoc, предварительно читая код, чтобы описывать реальное поведение, а не то, что задумывалось. CX Codex ★ 489звёзд репо refactor Субагент refactor для рефакторинга кодовой базы без изменения её поведения. Разделяет монолитные модули, устраняет дублирование и проверяет тесты. CX Codex ★ 489звёзд репо devops-engineer Субагент devops-engineer помогает настраивать CI/CD, контейнеры и инфраструктуру. Вызывайте его для пайплайна сборки, конфигурации Docker или сценария развёртывания. CX Codex ★ 489звёзд репо security-engineer Субагент security-engineer для проверки кода на уязвимости OWASP Top 10, аудита аутентификации и сканирования зависимостей. Строит карту угроз и выдаёт отчёт с приоритетами исправлений. CX Codex ★ 489звёзд репо validation Скилл validation для Claude Code проводит проект через сборку, линтеры и тесты и разбирает результат. Проверяет этапы работы агента и отдельные изменения. CX Codex +1 ★ 489звёзд репо product-manager Субагент product-manager превращает сырую идею фичи в PRD, приоритизированный бэклог и проверяемые юзер-стори, с которыми дальше работают другие агенты. CX Codex ★ 489звёзд репо ux-designer Субагент ux-designer проектирует пользовательские пути, интерфейсные паттерны и схемы экранов без написания фронтенд-кода. CX Codex ★ 489звёзд репо accessibility-specialist Субагент accessibility-specialist проверяет интерфейс по критериям WCAG, разбирает клавиатурную навигацию и ARIA. Подключайте его для аудита доступности веб-приложения. CX Codex ★ 489звёзд репо

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

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