Our test strategy focuses on unit tests for business logic.
Nossa estratégia de testes foca em unit tests para a lógica de negócio.Aula
Test strategy B1
Nível: B1
Objetivo
Discutir estratégia de testes em inglês, distinguindo unit, integration, end-to-end, regression e flaky tests, e priorizando o que adicionar com base na pirâmide de testes e em cobertura.
Explicação
A test strategy define *que* tipos de teste escrever, *onde* aplicar e *quando* executar. Em inglês técnico, ela normalmente responde a três perguntas: which tests are missing, what is the risk, and what do we run on every pull request.
The test pyramid
A test pyramid organiza os testes por escopo e velocidade:
- Unit tests na base: testam uma função ou classe isolada, sem I/O real. São rápidos, baratos e cobrem a lógica de negócio. Rodam em milissegundos.
- Integration tests no meio: testam como dois ou mais módulos合作 (ou um módulo com banco, fila, cache). São mais lentos e mais caros, mas detectam problemas de contrato entre componentes.
- End-to-end tests (E2E) no topo: percorrem o sistema inteiro, geralmente pela interface ou pela API externa. São lentos, frágeis e caros, mas detectam problemas que só aparecem no fluxo real.
A regra prática é: many unit tests, fewer integration tests, very few end-to-end tests. Se a pirâmide está invertida (muitos E2E e poucos unit), builds ficam lentos e o time confia menos nos testes.
Regression e flaky tests
- Regression test (ou regression suite) é um teste escrito para garantir que um bug já corrigido não volte. Quando um bug aparece em produção, o primeiro passo é escrever um teste que reproduza o bug — esse é o regression test.
- Flaky test é um teste que às vezes passa e às vezes falha, sem mudança no código. Causas comuns: dependência de tempo, ordem de execução, estado compartilhado, rede instável. Flaky tests corroem a confiança no CI: quando um time vê uma falha vermelha, a primeira reação passa a ser "é flake?" em vez de "o que quebrou?".
Coverage
Code coverage (ou simplesmente coverage) é a porcentagem de linhas, branches ou funções exercitadas pelos testes. Coverage alto não garante ausência de bugs, mas coverage baixo em código crítico é um sinal claro. Em geral, a meta não é 100%: o valor útil vem de cobrir o critical path (caminho crítico) e o edge case (caso de borda), não linhas triviais de getters.
Priorizando o que adicionar
Em uma conversa típica de planejamento, você vai ouvir frases como:
- `Let's start with unit tests for the pricing module — that's where the bug was.`
- `We don't need more end-to-end tests; one happy-path E2E is enough for this service.`
- `That test is flaky because it depends on the current time. Let's inject a clock.`
- `Coverage dropped from 80% to 65% on this file. Can we add a few targeted unit tests?`
- `We need a regression test for the bug we fixed last week.`
Vocabulário de ação
- to mock: substituir uma dependência real (banco, API externa) por uma versão controlada, para isolar o que está sendo testado.
- to stub: similar a mock, mas geralmente devolve dados fixos sem verificar como foi chamado.
- to assert: declarar o resultado esperado dentro de um teste (`assertEquals`, `assertTrue`).
- to run the suite: executar todos os testes de um projeto.
- to triage: classificar uma falha (flake real, bug novo, problema de ambiente).
Em priorização, use padrões como `we should prioritize`, `the highest risk is`, `we can defer that`, `it depends on the impact`.
Exemplos
| Inglês | Tradução | Observação |
|---|---|---|
| Most of our tests should be unit tests, with a smaller number of integration tests and very few end-to-end tests. | A maioria dos nossos testes deve ser unit, com um número menor de integration tests e muito poucos end-to-end tests. | Regra prática da test pyramid. |
| We added a regression test for the bug from ticket PAY-2041. | Adicionamos um regression test para o bug do ticket PAY-2041. | Regression test cobre um bug já corrigido. |
| This test is flaky — it fails about 10% of the time without any code change. | Esse teste é flaky — ele falha cerca de 10% das vezes sem nenhuma mudança de código. | Flaky = passa e falha sem causa aparente. |
| Coverage on the billing module is only 42%. Let's add unit tests for the critical paths. | A cobertura no módulo de billing é de apenas 42%. Vamos adicionar unit tests para os caminhos críticos. | Coverage mede porcentagem de código exercitada. |
| We need to mock the payment gateway so the test doesn't hit the real API. | Precisamos mockar o gateway de pagamento para que o teste não chame a API real. | Mock substitui dependências externas. |
| Let's prioritize unit tests for the pricing logic — that's where the regression risk is highest. | Vamos priorizar unit tests para a lógica de preço — é onde o risco de regressão é maior. | Priorizar = decidir ordem de implementação. |
| We can defer the end-to-end test until after the release; a unit test plus one integration test should be enough for now. | Podemos adiar o end-to-end test até depois do release; um unit test mais um integration test são suficientes por enquanto. | Defer = adiar conscientemente. |
| Every pull request runs the unit suite and the integration suite, but the full end-to-end suite runs only on main. | Cada pull request roda a unit suite e a integration suite, mas a end-to-end suite completa roda só na main. | Estratégia de execução por estágio de pipeline. |
Erros comuns
- Trocar a ordem: dizer `end-to-end unit test` ou `unit end-to-end test`; o correto é `end-to-end test` como um único tipo, distinto de `unit test`.
- Escrever `a flakiness test` em vez de `a flaky test` — flaky é adjetivo, não substantivo.
- Dizer `the coverage is 80%` sem contexto: especifique se é line coverage, branch coverage ou function coverage.
- Confundir `mock` e `stub`: mock verifica comportamento (como foi chamado), stub apenas devolve dados.
- Dizer `we need to test all the code` como meta: a meta útil é `cover the critical paths`, não todas as linhas.
- Usar `regression` como verbo: o verbo é `regress` ou, mais comum, `a bug regressed` / `to prevent a regression`.
- Confundir `regression test` (cobertura de bug antigo) com `regression` (quando algo que funcionava para de funcionar).
Prática guiada
Releia este cenário em voz alta e responda em inglês:
> O time de checkout tem um bug novo: em alguns pedidos, o cálculo de frete retorna 0 para clientes Premium. O time não tem testes automatizados no módulo de frete e roda apenas um happy-path E2E no CI.
- Que tipo de teste escrever primeiro? Resposta-modelo: `Start with a unit test for the shipping calculator, because that's where the bug is and unit tests are fast.`
- Vale a pena adicionar um E2E? Resposta-modelo: `Not yet. One E2E for the happy path is enough; we can add a second one for the Premium path later if needed.`
- O que dizer em uma retrospectiva sobre cobertura? Resposta-modelo: `Coverage on the shipping module is too low. Let's add unit tests for the discount rules before the next release.`
Resumo
Test strategy organiza unit tests (base, rápidos, isolados), integration tests (meio, validam contratos entre módulos) e end-to-end tests (topo, lentos e caros). Regression test cobre um bug já corrigido; flaky test falha sem mudança de código e destrói confiança no CI. Coverage mede quanto do código foi exercitado, e a meta útil é cobrir o critical path, não chegar a 100%. Priorize testes pelo risco de regressão, não pelo tamanho do arquivo.
Vocabulário
Palavras principais
The test pyramid suggests more unit tests than end-to-end tests.
A pirâmide de testes sugere mais unit tests do que end-to-end tests.A unit test should not depend on the database.
Um unit test não deve depender do banco de dados.The integration test verifies that the service writes to the database correctly.
O integration test verifica que o serviço grava no banco corretamente.An end-to-end test simulates a real user clicking through the checkout flow.
Um end-to-end test simula um usuário real clicando pelo fluxo de checkout.We have only one E2E in CI, and it covers the happy path.
Temos apenas um E2E no CI, e ele cobre o happy path.We wrote a regression test for the discount bug.
Escrevemos um regression test para o bug de desconto.That test is flaky because it depends on the system clock.
Esse teste é flaky porque depende do relógio do sistema.The build is red because of a flaky test, not a real failure.
O build está vermelho por causa de um teste flaky, não uma falha real.Line coverage on this module is 78%.
A line coverage neste módulo é 78%.We should cover the critical path with unit tests first.
Devemos cobrir o critical path com unit tests primeiro.Don't forget the edge case where the cart is empty.
Não esqueça o edge case em que o carrinho está vazio.The E2E covers only the happy path, not error scenarios.
O E2E cobre apenas o happy path, não cenários de erro.We mock the payment gateway in unit tests.
Nós mockamos o gateway de pagamento nos unit tests.The test stubs the user repository to return an admin user.
O teste cria um stub do repositório de usuários para retornar um admin.The test asserts that the total equals $42.
O teste afirma que o total é igual a $42.Let's triage the failing tests before the stand-up.
Vamos triar os testes que falharam antes da stand-up.The full test suite takes about 12 minutes to run.
A test suite completa leva cerca de 12 minutos para rodar.História
História: Test strategy B1
Nível: B1
História em inglês
The post-mortem meeting
On Monday morning, the payments team gathered for a short post-mortem about last week's incident. Marcus opened the meeting by saying, "A bug in the discount calculator returned 0 for some Premium customers. The fix was simple, but we had no test that caught it." Lina asked, "Did we have a regression test for that part of the code?" Marcus answered, "No, we didn't. And the only end-to-end test in CI covers the happy path, so it never saw the bug." Lina replied, "That explains it. Our test pyramid is upside down: we have one E2E and almost no unit tests for the pricing logic." "Coverage on the discount module is 22%," Marcus added. "Most of the lines are not exercised at all."
Building a new strategy
Lina suggested, "Let's start with unit tests for the discount calculator. That module has the highest regression risk." She continued, "We can mock the payment gateway in those tests, so they run in milliseconds and don't hit any real service." Marcus agreed, but he warned, "We also have a flaky test in the integration suite. It fails about once every ten runs." "Why is it flaky?" Lina asked. Marcus said, "It depends on the current time. When the test runs near midnight, the assertion breaks." Lina answered, "We should fix that test this week. A flaky test in CI is worse than no test at all, because the team stops trusting the build."
Prioritizing what comes next
At the end of the meeting, Marcus asked, "Do we need more end-to-end tests, or should we focus on the unit suite first?" Lina said, "Let's prioritize. We'll add a regression test for the bug we just fixed, then write unit tests for the critical path of the discount calculator." She added, "We can defer the new E2E until we have at least 70% line coverage on the pricing module." Marcus agreed, "That sounds reasonable. We'll also triage the flaky test today and decide whether to fix it or remove it." The meeting ended with a clear list: write the regression test, add unit tests for the critical path, fix or remove the flaky test, and revisit end-to-end coverage later.
Tradução linha por linha
| Inglês | Tradução |
|---|---|
| On Monday morning, the payments team gathered for a short post-mortem about last week's incident. | Na manhã de segunda-feira, o time de pagamentos se reuniu para um post-mortem curto sobre o incidente da semana passada. |
| Marcus opened the meeting by saying, "A bug in the discount calculator returned 0 for some Premium customers. The fix was simple, but we had no test that caught it." | Marcus abriu a reunião dizendo: “Um bug no calculador de desconto retornou 0 para alguns clientes Premium. A correção foi simples, mas não tínhamos nenhum teste que pegasse isso.” |
| Lina asked, "Did we have a regression test for that part of the code?" | Lina perguntou: “Tínhamos um regression test para essa parte do código?” |
| Marcus answered, "No, we didn't. And the only end-to-end test in CI covers the happy path, so it never saw the bug." | Marcus respondeu: “Não. E o único end-to-end test no CI cobre o happy path, então ele nunca viu o bug.” |
| Lina replied, "That explains it. Our test pyramid is upside down: we have one E2E and almost no unit tests for the pricing logic." | Lina respondeu: “Isso explica. Nossa test pyramid está de cabeça para baixo: temos um E2E e quase nenhum unit test para a lógica de preço.” |
| "Coverage on the discount module is 22%," Marcus added. "Most of the lines are not exercised at all." | “A coverage no módulo de desconto é de 22%”, completou Marcus. “A maioria das linhas nem é exercitada.” |
| Lina suggested, "Let's start with unit tests for the discount calculator. That module has the highest regression risk." | Lina sugeriu: “Vamos começar com unit tests para o calculador de desconto. Esse módulo tem o maior risco de regressão.” |
| She continued, "We can mock the payment gateway in those tests, so they run in milliseconds and don't hit any real service." | Ela continuou: “Podemos mockar o gateway de pagamento nesses testes, para que rodem em milissegundos e não chamem nenhum serviço real.” |
| Marcus agreed, but he warned, "We also have a flaky test in the integration suite. It fails about once every ten runs." | Marcus concordou, mas alertou: “Também temos um teste flaky na integration suite. Ele falha cerca de uma em cada dez execuções.” |
| "Why is it flaky?" Lina asked. | “Por que ele é flaky?”, perguntou Lina. |
| Marcus said, "It depends on the current time. When the test runs near midnight, the assertion breaks." | Marcus disse: “Ele depende do horário atual. Quando o teste roda perto da meia-noite, a asserção quebra.” |
| Lina answered, "We should fix that test this week. A flaky test in CI is worse than no test at all, because the team stops trusting the build." | Lina respondeu: “Devemos consertar esse teste esta semana. Um teste flaky no CI é pior do que nenhum teste, porque o time para de confiar no build.” |
| At the end of the meeting, Marcus asked, "Do we need more end-to-end tests, or should we focus on the unit suite first?" | No final da reunião, Marcus perguntou: “Precisamos de mais end-to-end tests, ou devemos focar na unit suite primeiro?” |
| Lina said, "Let's prioritize. We'll add a regression test for the bug we just fixed, then write unit tests for the critical path of the discount calculator." | Lina disse: “Vamos priorizar. Vamos adicionar um regression test para o bug que acabamos de corrigir e, depois, escrever unit tests para o critical path do calculador de desconto.” |
| She added, "We can defer the new E2E until we have at least 70% line coverage on the pricing module." | Ela acrescentou: “Podemos adiar o novo E2E até termos pelo menos 70% de line coverage no módulo de preços.” |
| Marcus agreed, "That sounds reasonable. We'll also triage the flaky test today and decide whether to fix it or remove it." | Marcus concordou: “Faz sentido. Vamos também triar o teste flaky hoje e decidir se consertamos ou removemos.” |
| The meeting ended with a clear list: write the regression test, add unit tests for the critical path, fix or remove the flaky test, and revisit end-to-end coverage later. | A reunião terminou com uma lista clara: escrever o regression test, adicionar unit tests para o critical path, consertar ou remover o teste flaky e revisitar a cobertura de end-to-end mais tarde. |
Notas de vocabulário
- regression test = teste escrito para garantir que um bug já corrigido não volte
- test pyramid = modelo que organiza unit (base), integration (meio) e end-to-end (topo)
- happy path = fluxo principal sem erros, geralmente o único coberto por E2E
- coverage = porcentagem de código exercitada pelos testes; medir, não meta em si
- flaky = intermitente, falha sem mudança de código; depende de tempo, rede ou estado compartilhado
- to mock = substituir uma dependência real por uma versão controlada em teste
- critical path = caminho mais importante do fluxo de negócio; o que deve ser coberto primeiro
- to prioritize = decidir ordem de implementação com base em risco e impacto
- to defer = adiar conscientemente, sem perder de vista
- to triage = classificar (corrigir, isolar ou remover) um teste problemático
Perguntas de compreensão
- What bug did the payments team discuss in the post-mortem?
- Why didn't the existing end-to-end test catch the bug?
- What did Lina say about the team's test pyramid?
- What is the flaky test in the integration suite flaky because of?
- Why did Lina say a flaky test is worse than no test at all?
- What did the team decide to prioritize first?
- When will the team revisit adding a new end-to-end test?
Prática com a história
- Responda em inglês: Why was the E2E test not enough to catch the discount bug?
- Reescreva começando com 'We should prioritize': Add unit tests for the discount calculator.
- Reescreva começando com 'The test is flaky because': It depends on the current time.
- Traduza: Podemos adiar o novo E2E até termos 70% de cobertura.
- Responda em inglês: What will the team do with the flaky test?
Prática
Exercícios e teste
A próxima melhoria é transformar esses arquivos em perguntas com resposta no navegador. Por enquanto, esta página já organiza o estudo e permite seguir a aula inteira sem abrir os arquivos manualmente.