The post has been translated automatically. Original language: Russian
The next part of the series is "The Red-Green-Refactor cycle: three steps in practice."
In many teams, the tests appear at the very end: the code has already been written, the deadline is near, and the tests are being added "for show." Such tests often repeat the implementation rather than checking the requirements. It's scary to change such a code: it's not clear what exactly will break and whether at least one test will notice it.
TDD (Test-Driven Development) suggests the reverse order: test first, then code. At the same time, the main idea is not in testing per se, but in quick feedback and in designing the code through its use.
How TDD works
Practice boils down to a short, repetitive cycle: write a test that crashes, write minimal code to make it pass, and then put the code in order. The method was described and popularized by Kent Beck, and Robert Martin formulated its in the form of three rules:
1. You cannot write working code until there is a falling test.
2. You can't write a test more than you need to crash (a compilation error is also considered a crash).
3. You can't write more code than you need to pass the current test.
How is this different from "tests after code"?
| Aspect | Post-code tests | TDD |
| When is the test being written? | After implementation | Before implementation |
| What defines the design | Ready-made implementation | Expected behavior |
| Feedback | In hours or days | In seconds or minutes |
| The risk of "superfluous" code | Tall | Below: the code is written for a specific test |
Why is this necessary?
- Clear requirements. To write a test, you need to clearly understand what the code should do.
- Simple and testable design. If it's inconvenient to write a test, it's a signal that the interface is poorly thought out.
- Safe refactoring. The test suite allows you to change the structure code and immediately see if the behavior is broken.
- Less debugging. The error is detected a minute after it appears, not a week later.
What TDD is not
TDD does not replace testers and does not guarantee the absence of bugs. It does not require one hundred percent coverage and is not suitable as the only way to check quality.: integration, acceptance, and research tests remain necessary. This is a developer's practice of making code more predictable, rather than a universal solution.
Result
TDD reverses the usual order: first , the expected behavior is described in the form of a test, then the code is written. The benefit is fast feedback, clear requirements, and safe changes. In the next part, we will analyze the "Red-Green-Refactor" cycle itself using a small example.
Have you tried writing tests before the code, and what turned out to be the most difficult: habit, complex requirements, or deadline pressure? Share your experience in the comments.
Следующая часть серии: «Цикл Red-Green-Refactor: три шага на практике».
Во многих командах тесты появляются в самом конце: код уже написан, срок близко, и тесты дописываются «для галочки». Такие тесты часто повторяют реализацию, а не проверяют требования. Изменить такой код страшно: непонятно, что именно сломается и заметит ли это хоть один тест.
TDD (Test-Driven Development, разработка через тестирование) предлагает обратный порядок: сначала тест, потом код. При этом главная идея не в тестировании как таковом, а в быстрой обратной связи и в проектировании кода через его использование.
Как устроен TDD
Практика сводится к короткому повторяющемуся циклу: написать тест, который падает, написать минимальный код, чтобы он прошёл, затем привести код в порядок. Метод описал и популяризировал Кент Бек, а Роберт Мартин сформулировал его в виде трёх правил:
1. Нельзя писать рабочий код, пока нет падающего теста.
2. Нельзя писать тест больше, чем нужно для падения (ошибка компиляции тоже считается падением).
3. Нельзя писать кода больше, чем нужно, чтобы пройти текущий тест.
Чем это отличается от «тесты после кода»
| Аспект | Тесты после кода | TDD |
| Когда пишется тест | После реализации | До реализации |
| Что определяет дизайн | Уже готовая реализация | Ожидаемое поведение |
| Обратная связь | Через часы или дни | Через секунды или минуты |
| Риск «лишнего» кода | Высокий | Ниже: код пишется под конкретный тест |
Зачем это нужно
- Ясные требования. Чтобы написать тест, нужно чётко понять, что должен делать код.
- Простой и тестируемый дизайн. Если тест писать неудобно, это сигнал, что интерфейс продуман плохо.
- Безопасный рефакторинг. Набор тестов позволяет менять структуру кода и сразу видеть, не сломалось ли поведение.
- Меньше отладки. Ошибка обнаруживается через минуту после появления, а не через неделю.
Чем TDD не является
TDD не заменяет тестировщиков и не гарантирует отсутствие багов. Он не требует стопроцентного покрытия и не подходит как единственный способ проверки качества: интеграционные, приёмочные и исследовательские тесты остаются нужными. Это практика разработчика, которая делает код более предсказуемым, а не универсальное решение.
Итог
TDD переворачивает привычный порядок: сначала описывается ожидаемое поведение в виде теста, затем пишется код. Выигрыш в быстрой обратной связи, чётких требованиях и безопасных изменениях. В следующей части разберём сам цикл «Red-Green-Refactor» на маленьком примере.
Пробовали ли вы писать тесты до кода, и что оказалось самым трудным: привычка, сложные требования или давление сроков? Поделитесь опытом в комментариях.