InsightsVibe Coding & AI Development
Vibe Coding & AI DevelopmentAI Coding AgentsAI-Generated CodeLaravelVibe CodingAI-Assisted CodingBest Practices

Getting Your AI Coding Agent to Actually Write Tests

A workflow for getting AI-generated tests that catch real bugs: write the contract first, prompt with examples and edge cases, generate tests in a fresh context, and challenge every assertion.

U

Umar Farooq

System Architect & Full-Stack Engineer

November 9, 2026
11 min read
Getting Your AI Coding Agent to Actually Write Tests

Getting Your AI Coding Agent to Actually Write Tests: A Recipe for AI Generated Tests for Code

AI coding agents write tests fast. The problem is that most AI generated tests for code agree with whatever the code already does. They pass on day one and miss the real bugs. This post gives you a recipe that fixes that. You write the contract first. The agent writes tests from the contract only. Then you verify the tests can actually fail.

Quick Answer: To get useful AI generated tests for code, write a plain-language contract first: inputs, outputs, and rules. Give the agent two good examples and two bad situations. Tell it to write tests from the contract only, never from the implementation. Then run the tests, break the code on purpose, and confirm the tests fail.

AI Generated Tests for Code: Why the Order Matters

Sonar's 2026 survey rated AI most effective at test generation, at 59 percent. No other engineering task scored higher. That sounds like good news. It hides a trap. An agent that reads your implementation first writes tests that describe what the code does. It ignores what the code should do. If the code has a bug, the tests learn the bug. Everything passes. You feel safe. You are not.

The fix is order. Contract first, tests second, implementation last. Or if the code already exists, contract first, tests from the contract in a fresh chat, then compare. I use this approach alongside the habits in how I use AI during software development. The agent is fast. You supply the judgment about what correct means.

Ingredients: What You Need Before You Start

Gather these before you open the agent. Skipping one is like baking without flour.

  • A plain-language contract: inputs, outputs, and rules for the feature. No code, just sentences.

  • Two good examples: real inputs with the exact expected outputs.

  • Two bad situations: invalid input, expired data, or a hostile value.

  • A fresh chat or context window for the agent, so it cannot see the implementation.

  • A working test command, usually php artisan test for Laravel apps.

  • Ten minutes of your own time to read the output. This step is not optional.

Step 1: Write the Contract First

Write down what the feature must do in plain sentences. List the inputs, the outputs, and the rules. Be exact about numbers and status codes. Here is an example contract for a discount endpoint.

POST /api/invoices/{id}/discount takes a coupon code. A valid 10% coupon reduces the total by exactly 10%. An expired coupon returns 422 and leaves the total unchanged. A coupon applied to a different invoice returns 404. Notice there is no code here. A non-technical teammate could read this and check it.

Step 2: Give Two Examples and Two Bad Situations

Examples make the contract concrete. Good situations show the happy path. Bad situations show the edges. For the discount endpoint, use these four. Valid: invoice total 1000, coupon SAVE10, expect total 900, status 200. Invalid: coupon EXPIRED1 on any invoice, expect 422, total unchanged. Boundary: coupon used at the exact expiry minute, expect 422. Hostile: coupon code with SQL characters, expect 422, total unchanged.

The hostile case matters more than the others. Models rarely invent attacks on their own. You have to demand them. A coupon field that reaches the database is an injection risk until proven otherwise.

Step 3: Prompt the Agent to Write Tests from the Contract Only

Open a fresh chat. Paste the contract and the examples. Tell the agent it may not look at the implementation. This is the key rule. The moment the agent reads your code, its tests start agreeing with your code. Use a prompt template like this one. Replace the bracketed parts with your own feature.

ROLE: You are a test writer. You write tests only from the contract below.

CONTRACT:
[Paste your plain-language contract here: inputs, outputs, rules.]

EXAMPLES:
[Two good examples with exact expected outputs.]
[Two bad situations: invalid, boundary, or hostile input.]

RULES:
- Never derive expected values from the implementation. Derive them from the contract only.
- Cover the happy path, one boundary case, and one failure case at minimum.
- Run php artisan test after writing and paste the full output.
- Explain failures before changing anything. Do not edit code to make tests pass.

Read that last rule twice. An agent that edits your code to make its own tests pass is hiding bugs, not fixing them. Failures get explained first, always.

Step 4: Run the Tests and Read the Output

Run the suite yourself. Do not trust a green checkmark from the agent alone. Read the output line by line. For every assertion, ask: can I trace this back to a line in my contract? If an assertion tests something the contract never said, flag it. The agent may have invented a rule. Invented rules in tests are as dangerous as invented rules in code. For the wider loop this fits into, SitePoint's test-generate-verify guide is worth a read.

Step 5: Break the Code on Purpose

This is the step most people skip, and it is the most important one. Change the discount from 10% to 5% in your code. Run the tests. They must fail. If they still pass, your tests prove nothing. Change it back when the tests fail as expected. This trick is called mutation testing. It answers the only question that matters: do these tests actually test anything?

A test suite that cannot fail is decoration. I would rather have five tests that catch real breaks than fifty that pass no matter what. Before you call the feature done, check the wider bar. Read your vibe-coded app works, is it actually production ready. Passing tests are one piece of that bar, not the whole bar.

Step 6: Add One Human-Written Assertion per Critical Path

Finish with your own eyes on the most important rule. Write one assertion yourself for each critical path. The agent did the bulk work. You own the verdict. Pest is a PHP testing tool popular with Laravel developers. It lets you write tests in a clean, readable style. Here is one human-written Pest test for the discount contract.

it('applies a valid 10 percent coupon to the invoice total', function () {
    $invoice = Invoice::factory()->create(['total' => 1000]);

    $response = $this->postJson("/api/invoices/{$invoice->id}/discount", [
        'coupon' => 'SAVE10',
    ]);

    $response->assertOk();
    // Contract says: 10% of 1000 = 900
    $response->assertJsonPath('data.total', 900);
});

That last line is the whole point. The expected value 900 comes from the contract, not from running the code and copying the result. If you want the full reference, the Laravel testing docs cover everything Pest and PHPUnit can do.

The Coupon Story: When Green Tests Hid a Real Bug

An agent once wrote a full green suite for a billing feature I was building. Every test passed. The code looked solid. Then I regenerated the tests from the contract in a fresh chat, following the recipe above. The new suite failed on the expiry check.

The old tests had copied the buggy behavior. The code applied the discount but never validated the coupon expiry. The first agent had read the implementation, learned the bug, and written tests that blessed it. Twelve passing tests, and none of them knew what the feature was supposed to do. The contract-first run caught it in minutes. For more on this failure mode, read this dev.to piece on adversarial tests. It shows the same pattern: tests that agree with the bug.

Five Things the Agent Will Never Write for You

The recipe has limits. Know them so you do not lean on the agent for what it cannot do.

  • Requirement-gap tests. The agent cannot test a rule you never told it about. If the contract is silent, the tests are silent.

  • Boundary reasoning. The agent will test the values you list. It will not discover the edge cases you missed.

  • Mutation-style challenges. Asking "would this test fail if the code were wrong" is your job. The agent assumes its tests are fine.

  • Cross-feature tests. The agent tests the feature in isolation. It will not check what your discount does to reporting, refunds, or tax totals.

  • Load behavior. A test that passes once says nothing about a thousand requests at once. For that, read scaling web apps from 100 to 10,000 users. Load is a separate discipline.

Questions Developers Ask About AI Generated Tests

Can AI write good tests for my code?

Yes, if you give it a contract first. Agents are fast and thorough at turning rules into test cases. The quality of the tests depends on the quality of your contract. A vague contract produces vague tests. Write the rules in plain sentences and the agent does the rest well.

How do I stop AI tests from repeating my bugs?

Never let the agent read the implementation before writing tests. Paste the contract into a fresh chat and tell it to derive expected values from the contract only. Then break the code on purpose and confirm the tests fail. That one check kills most bug-repeating tests.

What is Pest and should I use it for Laravel testing?

Pest is a PHP testing tool popular with Laravel developers. It sits on top of PHPUnit and gives you a cleaner syntax for writing tests. If you already use PHPUnit, Pest is an easy upgrade. If you are starting fresh on Laravel, start with Pest.

Do AI generated tests replace manual testing?

No. They replace the boring parts of test writing, not the thinking. You still decide what correct means. You still read the output. And you still add one human assertion per critical path. The agent is a fast typist with no judgment. Judgment stays with you.

How many tests should I ask the AI to write?

Ask for the happy path, one boundary case, and one failure case per rule in the contract. More is not always better. Ten sharp tests beat fifty shallow ones. If the suite takes too long to read, it is too big.

Why do my AI tests pass but the feature still breaks?

Because the tests describe what the code does, not what it should do. This happens when the agent reads your implementation first. Regenerate the tests from the contract in a fresh chat. If the new tests fail, you just found the gap between the code and the requirement.

Can I use this recipe with PHPUnit instead of Pest?

Yes. The recipe does not depend on the test tool. Contract first. Examples plus bad situations. Tests from the contract only. Run and read. Break on purpose. One human assertion. Every step works the same in PHPUnit, Pest, or any other framework.

AI Generated Tests for Code: Make This Your Default

Here is the recipe in short. Contract first. Examples second. The agent writes tests from the contract only. You read the output. You break the code to prove the tests fail. You add one human assertion per critical path. Six steps. The whole thing takes less time than debugging one production bug that your tests should have caught.

The agent will keep getting faster at writing tests. Your edge is knowing what correct means and refusing to accept tests that cannot fail. That is the standard I hold my own code to. Read writing clean and readable code for production systems. If your team wants help with this kind of testing discipline, reach out to me here. We can talk.

Umar Farooq - Full-Stack & AI Engineer

Umar Farooq

Author & Consultant

Specializes in Laravel, Next.js, and AI products. 5+ years enterprise experience with 80+ delivered platforms and full source code ownership.

Did you find this architecture breakdown useful?