AIO APEX
Claude Opus 4.8 (also works well with GPT-5.4 and Gemini 3 Pro for most languages; for niche frameworks, verify generated syntax against current library docs)You just wrote a pricing function for checkout and need a real test suite before it ships, but you have 15 minutes before a deploy window and writing every edge case by hand from scratch would take an hour.Developer Tools

O test case generator que encontra os bugs que seus happy-path tests não detectam

Compartilhar:
O test case generator que encontra os bugs que seus happy-path tests não detectam

Why this prompt matters

Untested edge cases in pricing logic are exactly the kind of bug that reaches production silently and gets discovered when a customer gets charged $0 or a discount stacks incorrectly. A 2024 industry survey found that logic errors in boundary conditions account for a disproportionate share of production incidents precisely because they pass casual manual testing but fail on the exact inputs automated tests are designed to catch.

What we use it for

You just wrote a pricing function for checkout and need a real test suite before it ships, but you have 15 minutes before a deploy window and writing every edge case by hand from scratch would take an hour.

Prompt

Act as a senior QA engineer and test architect with deep experience in [LANGUAGE/FRAMEWORK, e.g. "Python with pytest" or "TypeScript with Jest"].

CONTEXT:
Function or feature to test: [PASTE YOUR FUNCTION, CLASS, OR FEATURE DESCRIPTION HERE]
What it's supposed to do: [ONE-SENTENCE DESCRIPTION OF THE INTENDED BEHAVIOR]
Inputs it receives: [LIST THE PARAMETERS/INPUTS AND THEIR EXPECTED TYPES OR RANGES]
Known constraints or business rules: [ANY VALIDATION RULES, RATE LIMITS, OR EDGE CONDITIONS YOU ALREADY KNOW ABOUT]

TASK:
Generate a comprehensive test suite for this function/feature. Cover four distinct categories of tests:
1. Happy path — normal, expected inputs that should succeed
2. Edge cases — boundary values, empty inputs, maximum/minimum values, unusual-but-valid inputs
3. Error scenarios — invalid inputs, malformed data, and how the function should fail (specific exception types, error codes, or return values)
4. Integration considerations — if this function interacts with external systems (database, API, file system), list what should be mocked and why

CONSTRAINTS:
- Use the testing framework and idioms specified in the context — do not default to a generic framework
- Every test must have a descriptive name that states what it verifies, not just "test1", "test2"
- For each test, include a one-line comment explaining WHY that case matters, not just what it checks
- Do not generate redundant tests that check the same logical branch twice under different names
- Flag any case where you're uncertain about the correct expected behavior rather than guessing silently — mark it with a `# VERIFY:` comment

OUTPUT FORMAT:
1. **Test Suite** — complete, runnable test code in the specified framework
2. **Coverage Summary** — a short table listing each test, its category (happy path/edge/error/integration), and what specific risk it catches
3. **Gaps I Couldn't Cover** — a list of scenarios that need clarification from the developer before a test can be written (ambiguous requirements, undocumented behavior, etc.)

Result

Input context: Python function `apply_discount(price: float, discount_pct: float, min_price: float = 0.01) -> float` that applies a percentage discount to a price, but never lets the result drop below `min_price`. Framework: pytest.

1. Test Suite (excerpt):

def test_applies_standard_discount_correctly():
    # Verifies the core discount math works for a typical case
    assert apply_discount(100.0, 20.0) == 80.0

def test_zero_discount_returns_original_price():
    # Edge case: 0% discount should be a no-op, not an error
    assert apply_discount(50.0, 0.0) == 50.0

def test_full_discount_respects_minimum_price_floor():
    # Edge case: 100% discount would give $0, but min_price floor must apply
    assert apply_discount(50.0, 100.0, min_price=1.0) == 1.0

def test_negative_discount_raises_value_error():
    # Error case: a negative discount is a business-logic violation, not a valid input
    with pytest.raises(ValueError):
        apply_discount(50.0, -10.0)

def test_discount_over_100_percent_raises_value_error():
    # Error case: discounts above 100% are nonsensical and should be rejected explicitly
    with pytest.raises(ValueError):
        apply_discount(50.0, 150.0)

def test_negative_price_raises_value_error():
    # Error case: negative prices should never reach this function, but defend anyway
    with pytest.raises(ValueError):
        apply_discount(-10.0, 20.0)

def test_very_small_price_with_discount_stays_above_minimum():
    # Edge case: floating point rounding near the min_price boundary
    result = apply_discount(0.02, 50.0, min_price=0.01)
    assert result >= 0.01

2. Coverage Summary:

TestCategoryRisk It Catches
test_applies_standard_discount_correctlyHappy pathCore math is wrong
test_zero_discount_returns_original_priceEdge caseOff-by-one logic breaks the no-discount case
test_full_discount_respects_minimum_price_floorEdge casePrice floor silently ignored, allowing $0 sales
test_negative_discount_raises_value_errorErrorInvalid input silently accepted, inflating price instead of erroring
test_discount_over_100_percent_raises_value_errorErrorNegative resulting price before floor is applied
test_negative_price_raises_value_errorErrorGarbage input from an upstream bug propagates silently
test_very_small_price_with_discount_stays_above_minimumEdge caseFloating point rounding pushes result just under the floor

3. Gaps I Couldn't Cover:

  • # VERIFY: Should `discount_pct=100` exactly (not over) be allowed, or does it also need special handling? The spec doesn't say if 100% is a valid edge or an error.
  • No information given on whether `price` and `discount_pct` should accept `None` — worth clarifying if this function is called from user input directly.
  • Currency rounding behavior (2 decimal places vs raw float) isn't specified — this affects several boundary test assertions and should be confirmed before merging.

A maioria dos desenvolvedores escreve testes apenas para os cenários em que já pensaram, o que significa que os testes basicamente confirmam o que o desenvolvedor já sabia, em vez de trazer à tona o que passou despercebido. A distância entre "meu código passa nos meus testes" e "meu código está realmente correto" reside quase inteiramente naqueles casos que ninguém pensou em documentar. Este prompt foi construído especificamente para caçar nessa lacuna.

Por que quatro categorias em vez de apenas "escreva testes"

Um prompt simples de "escreva testes unitários para esta função" tende a gerar testes para o caminho feliz e, no máximo, um caso de erro óbvio — porque esse é o caminho de menor resistência para qualquer escritor, humano ou modelo. Forçar quatro categorias explícitas — happy path, edge cases, error scenarios, integration considerations — muda o padrão de busca. Os edge cases forçam o modelo a pensar em limites: zero, negativo, máximo, vazio, nulo. Os error scenarios forçam a reflexão sobre o que deve falhar de forma ruidosa em vez de falhar silenciosamente, que é onde os bugs mais custosos costumam se esconder. As integration considerations capturam aquela classe de bug que só aparece quando uma dependência mockada da função se comporta de maneira diferente da produção.

Por que o prompt exige um comentário "porquê" em cada teste

Uma suíte de testes com cinquenta testes e nenhuma explicação do que cada um protege é quase tão difícil de manter quanto não ter nenhum teste — seis meses depois, ninguém sabe se um teste é essencial ou vestigial. Exigir uma justificativa de uma linha em cada teste transforma a suíte em documentação dos modos reais de falha da função, o que compensa toda vez que alguém precisar mexer naquele código no futuro e precisar saber o que pode quebrar.

Por que "Gaps I Couldn't Cover" é a seção mais valiosa

A maioria dos prompts de geração de testes para no código do teste. Este, propositalmente, não para — porque um modelo de IA gerando testes para uma função que ele não entende completamente às vezes vai chutar o comportamento esperado em vez de sinalizar a ambiguidade — e um chute errado embutido em um teste que passa é pior do que nenhum teste, pois gera uma falsa confiança. A instrução explícita de sinalizar incerteza com um comentário `# VERIFY:`, junto com uma seção de saída dedicada listando questões não resolvidas, converte a adivinhação silenciosa em uma lista explícita que um desenvolvedor pode resolver em dois minutos antes de fazer o merge.

Como adaptá-lo

O prompt é propositalmente agnóstico em relação a frameworks — troque o campo de linguagem/framework e o modelo usará pytest, Jest, JUnit, RSpec ou o que você especificar, desde que você nomeie explicitamente em vez de deixar implícito. Para código legado sem testes existentes, alimente a função junto com quaisquer pontos de chamada que você encontrar, pois estes geralmente revelam restrições que a assinatura da função sozinha não mostra.

testingprompt-engineeringsoftware-developmentunit-testsqa
Compartilhar: