AIO APEX
Claude Sonnet 4.6 or GPT-4o — both handle this well; Claude tends to produce more thorough edge case coverageYou've just written a pricing function, an authentication handler, or a data-processing pipeline — and you need to ship it tomorrow. You paste the function into this prompt and get back a full test suite with happy paths, boundary values, and error scenarios already written, so you can move to code review instead of spending 90 minutes hand-crafting tests.Developer Tools

Gere Suítes de Teste Completas a Partir da Descrição de uma Função

Compartilhar:
Gere Suítes de Teste Completas a Partir da Descrição de uma Função

Why this prompt matters

Skipping edge cases is where most production bugs live. A function that works for normal inputs but silently returns wrong results for empty strings, zero values, or concurrent writes will pass a cursory manual test and still break in production. Developers without a structured checklist miss 30-50% of edge cases on average — this prompt enforces completeness every time.

What we use it for

You've just written a pricing function, an authentication handler, or a data-processing pipeline — and you need to ship it tomorrow. You paste the function into this prompt and get back a full test suite with happy paths, boundary values, and error scenarios already written, so you can move to code review instead of spending 90 minutes hand-crafting tests.

Prompt

Act as a senior QA engineer and software testing expert with 10+ years of experience writing test suites for production-grade code.

I have a function or feature that needs comprehensive test coverage. Here is the description:

[PASTE YOUR FUNCTION/FEATURE DESCRIPTION, CODE SNIPPET, OR SPECIFICATION HERE]

Technology stack: [YOUR LANGUAGE AND FRAMEWORK — e.g., Python/pytest, JavaScript/Jest, TypeScript/Vitest, Java/JUnit, Go/testing]
Testing framework: [YOUR TESTING FRAMEWORK]
Code maturity: [NEW CODE / EXISTING CODE WITH KNOWN BUGS / REFACTORING IN PROGRESS]

Your task:
1. Generate a complete set of unit tests covering:
   - Happy path (standard inputs with expected outputs)
   - Edge cases (boundary values, empty inputs, maximum inputs, special characters)
   - Error scenarios (invalid inputs, type mismatches, null/undefined, out-of-range values)
   - State mutations (if the function has side effects, test them explicitly)
2. List integration test outlines (what you'd test at the integration layer, without writing full code)
3. Identify any untestable scenarios and explain why (dependency on external systems, timing issues, etc.)
4. Add a one-line comment above each test explaining what it's asserting and why it matters

Constraints:
- Tests must be independent — no test should rely on another's side effects
- Use descriptive test names in the format: [method]_[scenario]_[expected outcome]
- Do NOT mock anything unless you explain exactly why the mock is necessary
- Prioritize tests by impact: mark each as HIGH / MEDIUM / LOW risk

Output format:
## Unit Tests (with priority labels)
[Full test code in [YOUR TESTING FRAMEWORK]]

## Integration Test Outlines
[Bullet list of integration scenarios to cover]

## Untestable Scenarios
[List with explanations]

## Coverage Summary
[Estimated line/branch coverage and what's missing]

Result

Here is the full test suite for calculate_discount(price, coupon_code, user_tier) using Python/pytest:

import pytest
from pricing import calculate_discount

# [HIGH] Standard discount applied correctly for a valid coupon and premium user
def test_calculate_discount_valid_coupon_premium_user_applies_discount():
    assert calculate_discount(100.0, "SAVE20", "premium") == 80.0

# [HIGH] Free users receive no additional tier discount beyond coupon
def test_calculate_discount_valid_coupon_free_user_no_tier_bonus():
    assert calculate_discount(100.0, "SAVE20", "free") == 80.0

# [HIGH] Invalid coupon code returns full price without discount
def test_calculate_discount_invalid_coupon_returns_full_price():
    assert calculate_discount(100.0, "FAKECODE", "premium") == 100.0

# [HIGH] Price of zero returns zero regardless of coupon or tier
def test_calculate_discount_zero_price_returns_zero():
    assert calculate_discount(0.0, "SAVE20", "premium") == 0.0

# [MEDIUM] Negative price raises ValueError — cannot discount negative amounts
def test_calculate_discount_negative_price_raises_value_error():
    with pytest.raises(ValueError, match="Price must be non-negative"):
        calculate_discount(-50.0, "SAVE20", "premium")

# [MEDIUM] Empty coupon string treated as no coupon — full price returned
def test_calculate_discount_empty_coupon_no_discount():
    assert calculate_discount(100.0, "", "premium") == 100.0

# [MEDIUM] None coupon treated as no coupon — does not raise, returns full price
def test_calculate_discount_none_coupon_no_discount():
    assert calculate_discount(100.0, None, "premium") == 100.0

# [MEDIUM] Unknown user_tier defaults to free-tier behavior, no tier bonus
def test_calculate_discount_unknown_tier_defaults_to_free():
    assert calculate_discount(100.0, "SAVE20", "vip") == 80.0

# [LOW] Very large price value does not cause overflow or floating-point error
def test_calculate_discount_very_large_price_precision():
    result = calculate_discount(1_000_000.0, "SAVE20", "premium")
    assert abs(result - 800_000.0) < 0.01

# [LOW] Coupon code is case-insensitive — "save20" works like "SAVE20"
def test_calculate_discount_coupon_case_insensitive():
    assert calculate_discount(100.0, "save20", "premium") == 80.0

Integration Test Outlines

  • Apply coupon from the database — verify the discount matches the stored percentage for that coupon record
  • Apply discount to a cart with multiple line items — verify totals are recalculated correctly
  • Expired coupon in the database — verify calculate_discount returns full price and logs the expiry event
  • Concurrent requests with the same coupon (single-use coupon) — verify only one request succeeds

Untestable Scenarios

  • Real-time coupon expiry race condition — coupon expires between the validity check and the discount application; requires a database transaction test outside unit scope
  • External pricing API availability — if calculate_discount calls a third-party pricing service, that call cannot be reliably tested without a staging environment

Coverage Summary

Estimated line coverage: 94%. Estimated branch coverage: 87%. Missing: the internal retry logic on database timeout (lines 47-52) — requires a mock of the DB connection pool, which should be covered in an integration test.

Escrever testes é uma daquelas tarefas que os devs sabem que deveriam fazer a fundo, mas raramente fazem. Não por preguiça — é a pressão do tempo e a carga cognitiva de enumerar cada caso de borda do zero. Este prompt delega essa enumeração para a IA, permitindo que você foque em revisar o resultado em vez de gerá-lo.

O Que Torna Esse Prompt Diferente

A maioria dos prompts do tipo "escreva testes para este código" devolve meia dúzia de asserções no caminho feliz e pronto. Este prompt força um contrato diferente: a IA precisa passar por quatro categorias distintas antes de finalizar — caminho feliz, casos de borda, cenários de erro e mutações de estado. Essa estrutura pega os 30-50% de casos de borda que os desenvolvedores perdem rotineiramente quando escrevem testes sob pressão de tempo.

O formato da saída também importa. Exigir nomes descritivos de teste no padrão [method]_[scenario]_[expected outcome] garante que a suíte de testes continue legível meses depois, quando o autor original já não estiver por perto. Exigir um comentário explicativo em cada teste significa que um novo desenvolvedor consegue entender o que cada asserção está protegendo — não apenas o que ela faz.

Como Usar

Cole sua função, uma descrição em português claro ou até um documento de especificação no campo entre colchetes. Especifique seu idioma e framework — a IA vai produzir código executável, não pseudocódigo. Defina a flag de maturidade do código como EXISTING CODE WITH KNOWN BUGS e a IA também identificará caminhos prováveis de defeito com base na estrutura do código.

A restrição de mock é intencional. Mockar tudo é o caminho mais fácil para construir uma suíte de testes que passa, mas não dá confiança nenhuma. Ao exigir que a IA justifique qualquer mock que introduzir, você mantém a suíte de testes ancorada no comportamento real.

Rótulos de Prioridade

Cada teste recebe um rótulo de risco HIGH / MEDIUM / LOW. Isso permite pular os testes LOW durante um release com prazo apertado e voltar a eles no próximo sprint — sem perder o controle do que foi pulado. Também acelera o code review: revisores conseguem ver rapidamente se os caminhos de risco HIGH estão cobertos.

Funciona Melhor Com

Claude Sonnet 4.6 ou GPT-4o. Para funções complexas com condicionais profundamente aninhadas, o Claude tende a produzir cobertura de branch mais completa. Para código novo em frameworks mais modernos, o GPT-4o é igualmente competente. Ambos os modelos lidam com este prompt de forma confiável — não use um modelo menor para esta tarefa, pois eles frequentemente omitem cenários de erro.

testingprompt-engineeringdeveloper-productivityunit-testsqacoding
Compartilhar: