367 lines
18 KiB
Markdown
367 lines
18 KiB
Markdown
# AI-Aided Test-First Development
|
||
|
||
## Официальное название
|
||
|
||
**AI-aided test-first development** — официальное название от Thoughtworks Technology Radar (апрель 2023)
|
||
|
||
**Статус**: **TRIAL** в Thoughtworks Technology Radar — рекомендуется для экспериментов в production
|
||
|
||
---
|
||
|
||
## Альтернативные названия
|
||
|
||
- **Test-Driven Development with AI** (Builder.io, широко распространено)
|
||
- **AI-Enabled TDD / AI-TDD** (AgileМania, коммерческие тренинги)
|
||
- **TDD as AI Communication Protocol** (8th Light, концептуальное)
|
||
- **AI-assisted TDD** (общепринятое в индустрии)
|
||
- **Test-First AI Development** (академические источники)
|
||
|
||
---
|
||
|
||
## Методология
|
||
|
||
### Суть подхода
|
||
|
||
**Инверсия традиционного AI workflow:**
|
||
|
||
| Традиционный AI подход | AI-aided test-first |
|
||
|------------------------|---------------------|
|
||
| Prompt → AI generates code → Human writes tests | Human defines test requirements → AI generates tests → AI implements → Tests validate |
|
||
| AI controls scope | Tests control scope |
|
||
| Human validates after | Human specifies before |
|
||
| Context in conversation | Context in tests |
|
||
|
||
### Цикл разработки
|
||
|
||
1. **Human**: пишет test description или acceptance criteria в natural language
|
||
2. **AI**: генерирует failing test(s) на основе описания
|
||
3. **Human**: проверяет и корректирует тесты (they define "done")
|
||
4. **AI**: имплементирует минимальный код для прохождения тестов
|
||
5. **Tests**: автоматически валидируют (binary pass/fail)
|
||
6. **AI**: рефакторит при необходимости (tests as safety net)
|
||
7. **Repeat**: для следующей фичи
|
||
|
||
### Ключевые принципы
|
||
|
||
- **Tests as specification** — тесты = compressed context для AI
|
||
- **Binary validation** — clear, measurable goal (pass/fail) вместо subjective review
|
||
- **Human architect, AI implementer** — разработчик проектирует поведение, AI печатает код
|
||
- **Guard rails** — тесты предотвращают AI hallucinations и scope creep
|
||
- **Fast feedback** — instant validation вместо manual code review
|
||
|
||
---
|
||
|
||
## Преимущества
|
||
|
||
### Для разработчика
|
||
|
||
- ✅ **Контроль над scope** — тесты определяют границы, AI не может "увлечься"
|
||
- ✅ **Сохранение навыков** — developer остаётся в роли architect/designer
|
||
- ✅ **Clear communication** — тесты = unambiguous specification для AI
|
||
- ✅ **Reduced cognitive load** — не нужно держать весь контекст в голове
|
||
- ✅ **Instant validation** — automated tests вместо manual review
|
||
|
||
### Для AI
|
||
|
||
- ✅ **Clear goal** — binary pass/fail проще чем "good code"
|
||
- ✅ **Structured context** — test suite как compressed requirements
|
||
- ✅ **Reduced hallucinations** — тесты ограничивают пространство решений
|
||
- ✅ **Measurable progress** — количество passing tests
|
||
|
||
### Для команды
|
||
|
||
- ✅ **Consistent quality** — junior + AI align с architectural style команды
|
||
- ✅ **Living documentation** — тесты документируют поведение
|
||
- ✅ **Faster onboarding** — AI помогает новичкам писать код в team's style
|
||
- ✅ **Reduced tech debt** — TDD предотвращает "vibe coding"
|
||
|
||
---
|
||
|
||
## Какую проблему решает
|
||
|
||
### Проблемы AI-кодинга без TDD
|
||
|
||
1. **Hallucinations и incorrect implementations** — AI генерирует код, который компилируется но не работает правильно
|
||
2. **Scope creep** — AI добавляет "полезные" фичи, которые не требовались
|
||
3. **Context rot** — AI теряет контекст в длинных сессиях, повторяет ошибки
|
||
4. **Untestable code** — AI генерирует tightly coupled код без учёта тестируемости
|
||
5. **Accumulating technical debt** — "move fast and break things" без safety net
|
||
6. **Developer skill atrophy** — разработчики становятся copy-paste operators
|
||
7. **Ambiguous requirements** — AI интерпретирует prompt по-своему
|
||
|
||
### Решение через TDD
|
||
|
||
- **Binary validation** → hallucinations caught immediately
|
||
- **Tests define scope** → AI cannot exceed test requirements
|
||
- **Tests = persistent context** → no context rot, reusable across sessions
|
||
- **Design for testability** → forces better architecture
|
||
- **Regression prevention** → existing tests catch breaks
|
||
- **Developer stays architect** → designs behavior, AI implements
|
||
- **Unambiguous spec** → failing test = clear goal
|
||
|
||
---
|
||
|
||
## Авторитетные источники
|
||
|
||
### Thoughtworks Technology Radar (2023-2025)
|
||
|
||
- **[AI-aided test-first development](https://www.thoughtworks.com/en-us/radar/techniques/ai-aided-test-first-development)** (апрель 2023)
|
||
- **Статус**: TRIAL — "we've seen promising results"
|
||
- **Применение**: junior developers + AI align с team's architectural style
|
||
- **Подход**: generate tests with ChatGPT → developer implements → или AI implements с test-first constraint
|
||
|
||
### DORA Report 2025 (Google Cloud)
|
||
|
||
- **[State of AI-Assisted Software Development 2025](https://dora.dev/research/2025/dora-report/)**
|
||
- **Главная находка**: "AI is an amplifier, not a fix" — усиливает существующие практики
|
||
- **TDD impact**: организации с strong testing practices получают больше выгоды от AI
|
||
- **[Google Cloud Blog](https://cloud.google.com/discover/how-test-driven-development-amplifies-ai-success)** (январь 2026): "TDD amplifies AI success"
|
||
- **Цитата**: "Quality practices such as TDD help organizations harness AI's productivity gains while maintaining stability"
|
||
|
||
### Kent Beck (создатель TDD и XP)
|
||
|
||
- **[Pragmatic Engineer Podcast](https://newsletter.pragmaticengineer.com/p/tdd-ai-agents-and-coding-with-kent)** (июнь 2025)
|
||
- **[YouTube Interview](https://www.youtube.com/watch?v=aSXaxOdVtAQ)** "TDD, AI agents and coding with Kent Beck"
|
||
- **Цитата**: "TDD is a superpower when working with AI. I communicate things the Genie missed in terms of tests"
|
||
- **Практика**: запускает тесты каждые 300ms чтобы "catch the genie"
|
||
- **LinkedIn**: "The genie doesn't want to do TDD. It wants to go fast. You have to force red-green-refactor"
|
||
|
||
### 8th Light (Software Consultancy)
|
||
|
||
- **[TDD: The Missing Protocol for Effective AI Collaboration](https://8thlight.com/insights/tdd-effective-ai-collaboration)** (июль 2025)
|
||
- **Тезис**: TDD breaks problems into small, testable behaviors → structured context для AI
|
||
- **Вывод**: TDD не просто best practice, это communication protocol
|
||
|
||
### Builder.io Engineering
|
||
|
||
- **[Test-Driven Development with AI](https://www.builder.io/blog/test-driven-development-ai)** (август 2025)
|
||
- **Тезис**: "AI turns TDD's weaknesses into strengths"
|
||
- **Анализ**: AI thrives on clear, measurable goals — binary test = clearest goal
|
||
- **Практика**: AI generates boilerplate tests, developer focuses на edge cases
|
||
|
||
---
|
||
|
||
## Формальные спеки и фреймворки
|
||
|
||
### AgileМania: AI-Enabled TDD Certification
|
||
|
||
- **[AI-Enabled Test-Driven Development (AI-TDD) Training](https://agilemania.com/test-driven-development-tdd-with-ai-training)** (декабрь 2024)
|
||
- **Формат**: 1-day hands-on certification course
|
||
- **Охват**: fundamentals of TDD + AI pair programming + hands-on exercises
|
||
- **Статистика**: "By 2025, 85% of software projects incorporate AI tools"
|
||
- **Особенности**: фокус на практическую интеграцию GitHub Copilot и Claude в TDD workflow
|
||
|
||
### Galileo AI: TDD for AI Systems Framework
|
||
|
||
- **[Test-Driven Development for AI Systems](https://galileo.ai/blog/test-driven-development-ai-systems)** (январь 2026)
|
||
- **[TDD for AI System Architecture](https://galileo.ai/blog/tdd-ai-system-architecture)** (август 2025)
|
||
- **Особенности**: framework для тестирования самих AI-систем, не AI-assisted coding
|
||
- **Компоненты**:
|
||
- Model Quality Checklist
|
||
- Test-First Specification Template
|
||
- AI Component Testing Matrix
|
||
- **Применение**: production AI systems с guardrails
|
||
|
||
### Thoughtworks Structured Approach
|
||
|
||
- **[Technology Radar Entry](https://www.thoughtworks.com/en-us/radar/techniques/ai-aided-test-first-development)** (2023)
|
||
- **Методология**:
|
||
1. Reusable prompt "fragments" (tech stack + design patterns + team conventions)
|
||
2. Feature description + acceptance criteria
|
||
3. AI generates implementation plan → tests → code
|
||
- **Особенности**: enterprise-scale применение, интеграция в CI/CD
|
||
|
||
### Nimble Approach: TDD Protocol for AI
|
||
|
||
- **[How to Use TDD for Better AI Coding Outputs](https://nimbleapproach.com/blog/how-to-use-test-driven-development-for-better-ai-coding-outputs/)** (ноябрь 2025)
|
||
- **Особенности**: пошаговый protocol для AI prompting с TDD
|
||
- **Инструкции**: как структурировать prompts для генерации тестов первыми
|
||
|
||
### Qodo (ex-CodiumAI): AI Test Generation
|
||
|
||
- **[AI Code Assistants Revolutionizing TDD](https://www.qodo.ai/blog/ai-code-assistants-test-driven-development/)** (июль 2025)
|
||
- **Продукт**: Qodo Gen — AI test generation tool
|
||
- **Особенности**: интегрируется в IDE, генерирует unit tests automatically
|
||
- **Поддержка**: Python, JavaScript, TypeScript, Java
|
||
|
||
---
|
||
|
||
## Использование в Claude Code
|
||
|
||
### Нативная поддержка
|
||
|
||
**Claude Code** полностью поддерживает AI-aided test-first подход через:
|
||
|
||
1. **Explicit test-first prompts**:
|
||
```
|
||
"Создай failing test для функции calculateTax(), которая должна
|
||
обрабатывать случаи: positive income, zero income, negative income"
|
||
```
|
||
|
||
2. **Output styles для TDD**:
|
||
- `/output-style learning` — Claude объясняет почему тест failing и как его починить
|
||
- `/output-style explanatory` — подробное объяснение test design decisions
|
||
|
||
3. **MCP integration** — подключение test runners через Model Context Protocol
|
||
|
||
### Workflow в Claude Code
|
||
|
||
**Step 1: Test Requirements**
|
||
```
|
||
Prompt: "Напиши тесты для user authentication module:
|
||
- Valid credentials → success
|
||
- Invalid password → error with message
|
||
- Nonexistent user → error with message
|
||
- Empty fields → validation error"
|
||
```
|
||
|
||
**Step 2: Claude генерирует failing tests**
|
||
```typescript
|
||
describe('AuthService', () => {
|
||
test('authenticates user with valid credentials', async () => {
|
||
const result = await authService.login('user@example.com', 'password123')
|
||
expect(result.success).toBe(true)
|
||
expect(result.user).toBeDefined()
|
||
})
|
||
// ... остальные тесты
|
||
})
|
||
```
|
||
|
||
**Step 3: Запуск (все failing)**
|
||
```
|
||
Prompt: "Запусти тесты и покажи результаты"
|
||
Claude: *executes tests, shows all failures*
|
||
```
|
||
|
||
**Step 4: Implementation**
|
||
```
|
||
Prompt: "Имплементируй AuthService чтобы пройти эти тесты"
|
||
Claude: *generates minimal implementation*
|
||
```
|
||
|
||
**Step 5: Validation**
|
||
```
|
||
Prompt: "Запусти тесты снова"
|
||
Claude: *all tests pass*
|
||
```
|
||
|
||
**Step 6: Refactor**
|
||
```
|
||
Prompt: "Рефактор: выдели error handling в отдельный класс"
|
||
Claude: *refactors with tests as safety net*
|
||
```
|
||
|
||
### Best Practices для Claude Code
|
||
|
||
- **Используй Projects** — добавь testing framework docs в project knowledge
|
||
- **Custom instructions**: "Always generate tests before implementation. Run tests after each change."
|
||
- **Iterative approach** — один тест → implementation → следующий тест
|
||
- **Explicit commands**: "Run tests", "Show test coverage", "Refactor without breaking tests"
|
||
|
||
### Источники
|
||
|
||
- [Anthropic Engineering: Claude Code Best Practices](https://www.anthropic.com/engineering/claude-code-best-practices) (апрель 2025)
|
||
- [Pair Programming with Claude Code](https://shipyard.build/blog/claude-code-output-styles-pair-programming/) (сентябрь 2025)
|
||
|
||
---
|
||
|
||
## Использование в Cursor
|
||
|
||
### Нативная поддержка
|
||
|
||
**Cursor** имеет специальные возможности для TDD workflow:
|
||
|
||
1. **Composer Agent Mode** — multi-step task execution с test validation
|
||
2. **Inline test generation** — `Cmd/Ctrl + K` → "generate test for this function"
|
||
3. **Auto-run tests** — Cursor автоматически запускает тесты после генерации кода
|
||
4. **Test-aware refactoring** — проверяет, что рефакторинг не ломает тесты
|
||
|
||
### Workflow в Cursor
|
||
|
||
**Method 1: Inline TDD**
|
||
|
||
1. Напиши comment с test requirements: `// Test: calculateDiscount should return 10% for orders > $100`
|
||
2. `Cmd + K` → "Generate test from this comment"
|
||
3. Cursor генерирует failing test
|
||
4. `Cmd + K` на функции → "Implement to pass the test above"
|
||
5. Cursor автоматически запускает тесты
|
||
|
||
**Method 2: Composer TDD**
|
||
|
||
1. Открой Composer (`Cmd + I`)
|
||
2. Prompt: "Create feature X using TDD: write tests first, then implement"
|
||
3. Composer генерирует test file → implementation file → runs tests → показывает результаты
|
||
4. Если тесты не проходят, Composer автоматически исправляет
|
||
|
||
**Method 3: Chat TDD**
|
||
|
||
1. Chat panel: "I want to add feature Y. Let's start with tests."
|
||
2. Cursor генерирует test scenarios
|
||
3. Ты выбираешь какие тесты написать first
|
||
4. Cursor генерирует failing tests
|
||
5. "Now implement to pass these tests"
|
||
6. Cursor имплементирует + auto-runs tests
|
||
|
||
### Cursor-специфичные фичи
|
||
|
||
- **Multi-file test generation** — Cursor одновременно создаёт test file + implementation stub
|
||
- **Test coverage view** — показывает какие части кода покрыты тестами
|
||
- **Smart refactoring** — предлагает рефакторинг только если тесты проходят
|
||
- **Voice mode TDD** — можно проговаривать test requirements голосом
|
||
|
||
### Best Practices для Cursor
|
||
|
||
- **Rules for AI** (`.cursorrules`):
|
||
```
|
||
Always use test-driven development:
|
||
1. Generate failing tests first
|
||
2. Implement minimal code to pass
|
||
3. Refactor with tests as safety net
|
||
4. Run tests after every change
|
||
```
|
||
- **Composer для complex features** — пусть agent управляет TDD циклом
|
||
- **Inline для quick fixes** — fast test generation для single functions
|
||
- **Git worktrees** — Cursor может запускать TDD workflow в изолированных branches
|
||
|
||
### Источники
|
||
|
||
- [Cursor Official Docs](https://cursor.com)
|
||
- [Launchpad Lab: AI Coding with Windsurf - A New Approach to TDD](https://launchpadlab.com/blog/ai-coding-with-windsurf-a-new-approach-to-tdd/) (июнь 2025) — применимо к Cursor
|
||
- [Skywork AI: Cursor's AI Autocomplete in Pair Programming](https://skywork.ai/blog/cursor-1-7-ai-autocomplete-pair-programming-best-practices/) (сентябрь 2025)
|
||
|
||
---
|
||
|
||
## Ссылки
|
||
|
||
### Официальные источники
|
||
|
||
- [Thoughtworks Technology Radar: AI-aided test-first development](https://www.thoughtworks.com/en-us/radar/techniques/ai-aided-test-first-development) (апрель 2023)
|
||
- [DORA Report 2025: State of AI-Assisted Software Development](https://dora.dev/research/2025/dora-report/)
|
||
- [Google Cloud: How TDD Amplifies AI Success](https://cloud.google.com/discover/how-test-driven-development-amplifies-ai-success) (январь 2026)
|
||
|
||
### Авторитетные голоса
|
||
|
||
- [Kent Beck: TDD, AI agents and coding (Podcast)](https://newsletter.pragmaticengineer.com/p/tdd-ai-agents-and-coding-with-kent) (июнь 2025)
|
||
- [Kent Beck YouTube Interview](https://www.youtube.com/watch?v=aSXaxOdVtAQ)
|
||
- [8th Light: TDD as Missing Protocol for AI](https://8thlight.com/insights/tdd-effective-ai-collaboration) (июль 2025)
|
||
- [Builder.io: Test-Driven Development with AI](https://www.builder.io/blog/test-driven-development-ai) (август 2025)
|
||
|
||
### Спеки и фреймворки
|
||
|
||
- [AgileМania: AI-Enabled TDD Training](https://agilemania.com/test-driven-development-tdd-with-ai-training)
|
||
- [Galileo AI: TDD for AI Systems](https://galileo.ai/blog/test-driven-development-ai-systems) (январь 2026)
|
||
- [Nimble Approach: TDD Protocol for AI](https://nimbleapproach.com/blog/how-to-use-test-driven-development-for-better-ai-coding-outputs/) (ноябрь 2025)
|
||
- [Qodo: AI Code Assistants & TDD](https://www.qodo.ai/blog/ai-code-assistants-test-driven-development/) (июль 2025)
|
||
|
||
### Практические руководства
|
||
|
||
- [Anthropic: Claude Code Best Practices](https://www.anthropic.com/engineering/claude-code-best-practices) (апрель 2025)
|
||
- [Atomic Spin: How I Made AI Respect TDD](https://spin.atomicobject.com/make-ai-respect-tdd/) (январь 2026)
|
||
- [Ready Set Cloud: TDD with AI - The Right Way](https://www.readysetcloud.io/blog/allen.helton/tdd-with-ai/) (октябрь 2023)
|
||
|
||
### Дополнительные ресурсы
|
||
|
||
- [Phil Parsons: Relevance of TDD in AI Workflow](https://philparsons.co.uk/blog/the-relevance-of-tdd-in-an-ai-workflow/)
|
||
- [Code Manship: Why TDD Works in AI Programming](https://codemanship.wordpress.com/2026/01/09/why-does-test-driven-development-work-so-well-in-ai-assisted-programming/) (январь 2026)
|
||
- [NOPC Accelerate: TDD Guide 2025](https://www.nopaccelerate.com/test-driven-development-guide-2025/) (сентябрь 2025)
|