Testes

BDD, ATDD e TDD: o que cada sigla resolve

São as três siglas que mais geram confusão — e justamente por isso aparecem o tempo todo na rotina de QA. As três compartilham a mesma ideia central: escrever o teste antes do código. A diferença está em quem escreve, em que nível e com qual objetivo. Entender essa divisão é o que separa repetir a sigla de saber aplicá-la.

O mapa mental

Antes dos detalhes, uma visão de cima. As três técnicas vivem em camadas diferentes do mesmo fluxo:

            "Estamos construindo a coisa certa?"   (negócio)
                                 │
        ┌────────────────────────┴────────────────────────┐
        │                                                  │
       BDD ──────────────► ATDD ──────────────►          TDD
  comportamento do        critério de aceite        unidade de código
  ponto de vista do        vira teste de             vira teste técnico
  usuário/negócio          aceitação executável      (red-green-refactor)
        │                          │                        │
   linguagem ubíqua         "três amigos"            desenvolvedor sozinho
   (Gherkin)                PO + Dev + QA            no editor, em segundos
        │                          │                        │
        └──────────► foco no "o quê" ◄──────┐    foco no "como"
                                            └── "Estamos construindo
                                                 a coisa do jeito certo?"

TDD — Test-Driven Development

É o nível mais técnico e o mais granular. O desenvolvedor escreve um teste de unidade que falha, faz o mínimo para passar e refatora — o ciclo red-green-refactor. O alvo é o design interno do código: classes, funções, regras de negócio isoladas.

// Red — o teste falha porque a regra ainda não existe
test('aplica 10% de desconto acima de R$ 100', () => {
  expect(calcularTotal(150)).toBe(135);
});

// Green — o mínimo para passar
function calcularTotal(valor) {
  return valor > 100 ? valor * 0.9 : valor;
}

// Refactor — agora com a rede de segurança verde

TDD não é sobre cobertura — é sobre design guiado pelo uso. O detalhe importante para QA: o teste de TDD fala a língua do código (calcularTotal, toBe(135)), não a do usuário.

ATDD — Acceptance-Test-Driven Development

Sobe um nível. Antes de programar, o time transforma o critério de aceite da história em um teste de aceitação concreto. A peça-chave é a conversa conhecida como "três amigos" (Product Owner, Dev e QA): juntos eles definem, com exemplos, o que significa "pronto" antes de uma linha de código existir.

ATDD previne o bug mais caro de todos: construir corretamente a funcionalidade errada. O teste de aceite é o acordo escrito de "feito".

O QA costuma ser o protagonista aqui — é quem pergunta "e se o valor for negativo?", "e o limite exato de R$ 100, entra no desconto ou não?". Essas perguntas viram os testes de aceitação.

BDD — Behavior-Driven Development

É a evolução do ATDD com foco em linguagem. O BDD propõe descrever o comportamento do sistema do ponto de vista do usuário, numa linguagem ubíqua que negócio e técnica leem igual. Na prática, isso aparece como cenários em Gherkin (Given / When / Then):

Funcionalidade: Desconto no carrinho

  Cenário: Compra acima do limite ganha desconto
    Dado um carrinho com R$ 150,00
    Quando o cliente finaliza a compra
    Então o total cobrado deve ser R$ 135,00

Esse cenário é legível pelo negócio e executável pela automação (via Cucumber, Behave, SpecFlow…). É o que se chama de documentação viva: a especificação e o teste são o mesmo artefato. Detalhei a sintaxe no post sobre Gherkin e Given-When-Then.

Lado a lado

TDDATDDBDD
PerguntaEstou construindo certo?Construí a coisa certa?O sistema se comporta como o usuário espera?
NívelUnidade / códigoAceitação / históriaComportamento / funcionalidade
Quem escreveDesenvolvedorTime (3 amigos)Time, em linguagem de negócio
LinguagemCódigo de testeExemplos / critériosGherkin (Given-When-Then)
ArtefatoTeste unitárioTeste de aceitaçãoCenário executável
FocoComoO quêO quê + comunicação

Como elas convivem

O erro é tratá-las como concorrentes. Na prática elas se empilham: o BDD/ATDD definem o quê entregar (poucos cenários de alto nível, perto do topo da pirâmide de testes), e o TDD garante que cada pedacinho do código que sustenta aquele comportamento nasça correto (muitos testes rápidos, na base). Um time maduro usa os três ao mesmo tempo, em camadas.

Armadilhas que aparecem no dia a dia

  • "BDD é uma ferramenta." Não. BDD é uma prática de colaboração. Cucumber é ferramenta; escrever Gherkin sem a conversa dos três amigos é só sintaxe nova para o mesmo silo de sempre.
  • Gherkin descrevendo cliques. "Dado que clico no botão azul" amarra o cenário à tela. O comportamento é o quê acontece, não como se navega.
  • Confundir ATDD com "QA escreve teste depois". O "driven" é literal: o teste vem antes e guia o desenvolvimento.
  • TDD virar dogma. Brilha em regra de negócio; para um protótipo descartável, pode ser exagero. Use a ferramenta certa para o contexto.

Conclusão

TDD cuida do código, ATDD cuida do acordo, BDD cuida da conversa — e os três cuidam de testar antes. Saber em que camada cada um atua é o que permite escolher a técnica certa para o problema na sua frente, em vez de aplicar todas por reflexo.

These are the three acronyms that cause the most confusion, which is exactly why they show up all the time in a QA's routine. All three share the same core idea: write the test before the code. The difference lies in who writes it, at what level, and to what end. Understanding that split is what separates repeating the acronym from knowing how to apply it.

The mental map

Before the details, a view from above. The three techniques live in different layers of the same flow:

            "Are we building the right thing?"   (business)
                                 │
        ┌────────────────────────┴────────────────────────┐
        │                                                  │
       BDD ──────────────► ATDD ──────────────►          TDD
  behavior from the        acceptance criterion      unit of code
  user/business            becomes an executable     becomes a technical
  point of view            acceptance test           test (red-green-refactor)
        │                          │                        │
   ubiquitous language       "three amigos"            developer alone
   (Gherkin)                 PO + Dev + QA             in the editor, in seconds
        │                          │                        │
        └──────────► focus on the "what" ◄──────┐    focus on the "how"
                                                └── "Are we building
                                                     the thing the right way?"

TDD — Test-Driven Development

This is the most technical and most granular level. The developer writes a failing unit test, does the minimum to make it pass, and refactors: the red-green-refactor cycle. The target is the internal design of the code: classes, functions, isolated business rules.

// Red — the test fails because the rule does not exist yet
test('applies 10% discount above $100', () => {
  expect(calcularTotal(150)).toBe(135);
});

// Green — the minimum to make it pass
function calcularTotal(valor) {
  return valor > 100 ? valor * 0.9 : valor;
}

// Refactor — now with the green safety net

TDD is not about coverage; it is about design driven by usage. The important detail for QA: a TDD test speaks the language of the code (calcularTotal, toBe(135)), not the user's.

ATDD — Acceptance-Test-Driven Development

One level up. Before coding, the team turns the story's acceptance criterion into a concrete acceptance test. The key piece is the conversation known as the "three amigos" (Product Owner, Dev, and QA): together they define, with examples, what "done" means before a single line of code exists.

ATDD prevents the most expensive bug of all: correctly building the wrong feature. The acceptance test is the written agreement of "done".

QA is usually the protagonist here: the one asking "what if the amount is negative?", "and the exact $100 limit, does it get the discount or not?". Those questions become the acceptance tests.

BDD — Behavior-Driven Development

This is the evolution of ATDD with a focus on language. BDD proposes describing the system's behavior from the user's point of view, in a ubiquitous language that business and tech read the same way. In practice, this shows up as Gherkin scenarios (Given / When / Then):

Feature: Cart discount

  Scenario: Purchase above the limit gets a discount
    Given a cart with $150.00
    When the customer checks out
    Then the total charged should be $135.00

This scenario is readable by the business and executable by automation (via Cucumber, Behave, SpecFlow…). This is what is called living documentation: the specification and the test are the same artifact. I covered the syntax in the post on Gherkin and Given-When-Then.

Side by side

TDDATDDBDD
QuestionAm I building it right?Did I build the right thing?Does the system behave the way the user expects?
LevelUnit / codeAcceptance / storyBehavior / feature
Who writes itDeveloperTeam (3 amigos)Team, in business language
LanguageTest codeExamples / criteriaGherkin (Given-When-Then)
ArtifactUnit testAcceptance testExecutable scenario
FocusHowWhatWhat + communication

How they coexist

The mistake is treating them as competitors. In practice they stack: BDD/ATDD define what to deliver (a few high-level scenarios, near the top of the test pyramid), and TDD ensures that every little piece of code supporting that behavior is born correct (many fast tests, at the base). A mature team uses all three at once, in layers.

Pitfalls that show up day to day

  • "BDD is a tool." No. BDD is a collaboration practice. Cucumber is a tool; writing Gherkin without the three amigos conversation is just new syntax for the same old silo.
  • Gherkin describing clicks. "Given I click the blue button" ties the scenario to the screen. Behavior is what happens, not how you navigate.
  • Confusing ATDD with "QA writes the test afterwards". The "driven" is literal: the test comes first and guides development.
  • TDD turning into dogma. It shines on business rules; for a throwaway prototype, it may be overkill. Use the right tool for the context.

Conclusion

TDD takes care of the code, ATDD takes care of the agreement, BDD takes care of the conversation, and all three take care of testing first. Knowing which layer each one operates in is what lets you choose the right technique for the problem in front of you, instead of applying all of them by reflex.

Leia também

Voltar ao blog