The post has been translated automatically. Original language: Russian
This is the first part of a series of nine posts about BDD. Next , we'll look at the discussion of examples, the Gherkin language, automation, an end-to-end example, a test pyramid, typical errors, team implementation, and the limits of applicability.
A familiar situation: the customer described the function in one way, the developer understood it in the second, and the tester checked it in the third. In the demo, it turns out that everyone was right in their own way, but no one is satisfied with the result. The Behavior-Driven Development (BDD) approach has become one of the ways to reduce the risk of such misunderstandings.
What is BDD?
BDD, or behavior-driven development, is an approach in which the expected behavior of a system is described using concrete examples and in a language that is understandable to everyone. These examples are understood by business analysts, developers, and testers. Later, they can be turned into automated tests and up-to-date documentation.
The approach developed in the mid-2000s as a development of TDD ideas. Its author is considered to be Dan "Northa": he suggested shifting the focus from the word "test" to the word "behavior" and making the conversation about requirements common to the entire team.
Three ideas of BDD
1. A common language. All participants call things the same way: in terms of the subject area, not technical jargon.
2. Concrete examples instead of abstract requirements. "The system must correctly process discounts" is open to interpretation. "With a 10% discount on an order of 10,000 tenge, 9,000 tenge is payable" is more difficult to interpret.
3. Executable documentation. The examples are written in a formalized form, so they can be run as tests and checked to see if the system matches the description.
How does BDD differ from TDD
| TDD | BDD | |
| The main question | Does this piece of code work correctly? | Does the system do what the business needs? |
| Language | Programming language | The language of the subject area |
| Participants | Mainly a developer | Business, development, testing |
| Level | Modules and functions | System behavior, user scenarios |
The approaches do not conflict: BDD defines the external behavior, and TDD helps to implement the components inside.
What is BDD for?
• align the understanding of the task before writing the code;
• Find missing scenarios and exceptions during the discussion stage;
• get documentation that does not silently become obsolete, because it is checked automatically.;
• Link requirements and tests: each example becomes a test.
Result
BDD is primarily about conversation and general understanding, and only then about tools. ""In the next part, " "Discovery: "three Amigos" and Example Mapping," we'll look at how the examples are discussed and why it provides the main benefits.
Have you ever encountered a situation where the team understood the same task differently? Tell us in the comments.
Это первая часть серии из девяти постов о BDD. Дальше разберём обсуждение примеров, язык Gherkin, автоматизацию, сквозной пример, тестовую пирамиду, типичные ошибки, внедрение в команде и границы применимости.
Знакомая ситуация: заказчик описал функцию одним образом, разработчик понял её вторым, а тестировщик проверил по третьему. На демо выясняется, что каждый был по-своему прав, а результат никого не устраивает. Одним из способов снизить риск такого недопонимания стал подход Behavior-Driven Development (BDD).
Что такое BDD
BDD, или разработка через поведение, это подход, при котором ожидаемое поведение системы описывается на конкретных примерах и понятным для всех языком. Эти примеры понимают бизнес-аналитики, разработчики и тестировщики. Позже их можно превратить в автоматические тесты и актуальную документацию.
Подход сложился в середине 2000-х как развитие идей TDD. Его автором принято считать Дэна Норта: он предложил сместить акцент со слова «тест» на слово «поведение» и сделать разговор о требованиях общим для всей команды.
Три идеи BDD
1. Общий язык. Все участники называют вещи одинаково: терминами предметной области, а не техническим жаргоном.
2. Конкретные примеры вместо абстрактных требований. «Система должна корректно обрабатывать скидки» открыто для трактовок. «При скидке 10% на заказ в 10 000 тенге к оплате 9 000 тенге» трактовать сложнее.
3. Исполняемая документация. Примеры записываются в формализованном виде, поэтому их можно запускать как тесты и проверять, соответствует ли система описанию.
Чем BDD отличается от TDD
| TDD | BDD | |
| Главный вопрос | Правильно ли работает этот кусок кода? | Делает ли система то, что нужно бизнесу? |
| Язык | Язык программирования | Язык предметной области |
| Участники | В основном разработчик | Бизнес, разработка, тестирование |
| Уровень | Модули и функции | Поведение системы, пользовательские сценарии |
Подходы не конфликтуют: BDD задаёт внешнее поведение, а TDD помогает реализовать компоненты внутри.
Для чего нужен BDD
• выровнять понимание задачи до написания кода;
• найти пропущенные сценарии и исключения на этапе обсуждения;
• получить документацию, которая не устаревает молча, потому что её проверяют автоматически;
• связать требования и тесты: каждый пример становится проверкой.
Итог
BDD в первую очередь про разговор и общее понимание, а уже потом про инструменты. В следующей части, «Discovery: “три амиго” и Example Mapping», разберём, как проходит обсуждение примеров и почему именно оно даёт основную пользу.
Сталкивались ли вы с ситуацией, когда команда по-разному поняла одну и ту же задачу? Расскажите в комментариях.