Manuel B. Garcia

Manuel B. Garcia serves as the Senior Director for Educational Technology and Digital Learning at FEU Institute of Technology, Manila, Philippines. Read More

Contact Info

1607, FEU Tech Building,
P. Paredes St, Sampaloc,
Manila, Philippines
mbgarcia@feutech.edu.ph

Follow Me

Can Generative AI Reliably Generate Tests for Its Own Code?

Generative AI can write useful tests for its own code, but passing those tests does not establish that the implementation is correct. Learn how shared assumptions, inadequate test coverage, and circular verification can undermine AI-generated tests.

730
Can AI Reliably Test Its Own Code? Guide 730 of 1196
01 · The Question

Can You Trust an AI System to Test the Code It Just Generated?

You ask a generative AI assistant to write a Python function that calculates scores from a research questionnaire. After receiving the code, you ask the same assistant to create unit tests. It produces several tests, executes them through an available coding environment, and reports that everything passes.

That seems reassuring. The code works, the tests pass, and the AI explains why the implementation is correct. But what if the AI misunderstood the scoring procedure in the first place?

If the same misunderstanding appears in both the function and its tests, the entire test suite could pass while the research calculation remains wrong. Researchers therefore need to distinguish AI's ability to generate executable tests from its ability to establish that those tests provide independent evidence of correctness.

02 · The Short Answer

AI Can Generate Useful Tests, but It Cannot Reliably Certify Its Own Code

In Brief

Generative AI can produce useful unit tests, suggest edge cases, and help automate verification of research code. However, tests generated by the same AI system that wrote the implementation cannot be assumed to provide reliable independent verification, because the code and tests may share incorrect assumptions, incomplete requirements, or the same misunderstanding of the intended calculation.

AI-generated tests should be reviewed against researcher-defined requirements and independently established expected results. Their reliability depends on test quality, coverage of consequential behaviors, and whether the tests can detect plausible errors, not simply on whether they execute successfully or produce passing results.

03 · What You Need to Know

Why AI-Generated Tests Can Pass Even When the Code Is Wrong

What Does It Mean for AI to Generate Tests for Its Own Code?

Generative AI can assist with software testing in several ways. It may write unit tests for a function it generated, identify potential edge cases, suggest assertions, create mock inputs, or help interpret failed tests.

For example, an AI assistant might generate a function that calculates a composite questionnaire score and then produce a test asserting that five particular responses should yield a specified mean.

The test may be syntactically correct and executable. Whether it is scientifically meaningful depends on how the expected value was established.

In software testing, an oracle is the mechanism or source used to determine whether a test result is correct. For research code, the oracle might be an independently calculated value, a documented formula, an authoritative reference implementation, or a well-defined property that the function must satisfy.

AI can help express these expectations in executable form. The difficulty arises when it also invents the expectations without an independent basis for judging them.

The Central Problem: Shared Assumptions Between Code and Tests

Consider an AI system asked to calculate sample variance. The researcher intends the conventional sample variance, which divides the sum of squared deviations by the sample size minus one. The AI mistakenly implements division by the sample size, corresponding to a different variance calculation.

When asked to generate a test, the AI might calculate the expected result using the same incorrect denominator. The test passes because the implementation and expectation agree.

Yet agreement between two expressions of the same mistake does not establish correctness.

Internal consistency The generated implementation produces the result expected by the generated test.
Independent verification The implementation produces a result established from requirements or evidence independent of the implementation being tested.

Internal consistency is useful but insufficient. A test suite can be perfectly consistent with an incorrect interpretation of the research method.

This is why researcher-defined test cases and expected outcomes are particularly valuable when AI generates analytical code.

Why Passing Tests Can Create False Confidence

Automated testing frameworks generally report whether specified assertions passed or failed. They do not determine whether those assertions represent the correct scientific requirements.

A test may pass because the implementation is correct. It may also pass because the test checks an irrelevant property, uses an incorrect expected value, or overlooks the condition under which the function fails.

For example, a function intended to classify students as meeting a threshold might be tested only with values far above and below the cutoff. Those tests would not reveal whether the implementation incorrectly handles a value exactly equal to the threshold.

The problem is not that automated tests are unreliable by definition. It is that their evidentiary value depends on what they test and how their expectations were justified.

Researchers should therefore resist treating a passing test summary as a certification of methodological correctness.

Can AI Generate Tests That Detect Genuine Errors?

Yes. AI-generated tests can identify real defects, particularly when the requirements are clear and the model proposes cases that the researcher has not considered.

An AI assistant might suggest testing an empty dataset, duplicate identifiers, missing questionnaire items, invalid categories, or numerical boundary conditions. Such suggestions can improve the breadth of a test suite.

AI may also help translate existing research specifications into executable assertions, reducing the programming effort required to establish automated checks.

However, performance is task-dependent. A model that produces useful tests for a straightforward mathematical function may struggle with specialized statistical methods, domain-specific scoring rules, or complex data-processing workflows.

Researchers should evaluate the generated tests individually rather than assume that AI-generated test suites have a consistent level of reliability across tasks.

Why Test Coverage Does Not Establish Test Quality

Code coverage measures which parts of a program were executed during testing. Common coverage measures include statements and branches, although the exact metrics depend on the tooling.

AI can generate tests that increase coverage, but high coverage does not guarantee that the assertions detect incorrect behavior.

Suppose a test executes every line of a questionnaire-scoring function but checks only that the returned result is numeric. The test might achieve extensive statement coverage while failing to detect an incorrect scoring formula.

Coverage is therefore a diagnostic measure rather than a direct measure of scientific correctness.

A useful test suite should exercise important behaviors and compare results against meaningful expectations. Researchers should pay particular attention to operations that affect the analytical sample, variable construction, or reported estimates.

Can Mutation Testing Reveal Weak AI-Generated Tests?

Mutation testing is a software-testing technique in which small changes are deliberately introduced into an implementation to determine whether the test suite detects them.

For example, a mutation might replace a greater-than comparison with a greater-than-or-equal-to comparison, change an arithmetic operator, or alter a boundary condition.

If the tests fail after a meaningful mutation, the mutation is said to have been killed. If the altered implementation continues to pass, the tests may not adequately distinguish the intended behavior from that particular incorrect behavior.

Mutation testing can therefore help evaluate whether AI-generated tests are capable of detecting certain classes of errors.

However, not every mutation represents a meaningful defect. Some changes preserve equivalent behavior, while others affect code unrelated to the research requirements. A mutation score should not be interpreted as proof of scientific validity.

For consequential analytical functions, targeted mutation testing may be more informative than relying exclusively on test counts or statement coverage.

Would Using a Different AI Model Make the Tests Independent?

Using a different model may introduce some diversity into the testing process, but it does not automatically establish independence.

Different models can share training influences, common programming conventions, and similar misunderstandings of ambiguous instructions. They may also rely on the same incorrect specification supplied by the researcher.

If one model generates a function and another generates tests based on the same flawed description, both may reproduce the same methodological error.

Independent verification is better understood in terms of the evidentiary basis for expected outcomes than the number of models involved.

A manually calculated reference value, an authoritative formula, or a separately justified methodological specification may provide a stronger oracle than agreement between two AI systems.

Can AI-Generated Tests Be Useful Without Exact Expected Outputs?

Some functions are difficult to test because independently calculating an exact expected output is expensive or impractical. This is sometimes called the oracle problem.

In such situations, researchers can test properties that should hold even when the exact result is unknown.

For example, a function that sorts numerical values should preserve the number of observations and produce an ordered sequence. A function that converts proportions to percentages should preserve the relationship between the input and output values.

Metamorphic testing examines relationships between multiple executions. For instance, multiplying every observation by a constant should change the arithmetic mean by the same factor, assuming the function is intended to calculate an ordinary mean.

AI may help propose such properties, but researchers must verify that they are mathematically and methodologically appropriate. A plausible-sounding property can itself be incorrect.

What Happens When AI Writes Both the Code and Its Expected Outputs?

The greatest concern is not merely that the same model produced both artifacts. It is that the expected outputs may have been derived from the implementation rather than from the intended specification.

Suppose an AI assistant generates a data-cleaning function and then executes it on sample records to create expected values for its tests. If the function incorrectly excludes a category of participants, the resulting expected dataset may reproduce the same exclusion.

The tests then protect the existing behavior, including the error.

Researchers should distinguish between characterization tests, which document what existing code currently does, and specification-based tests, which evaluate what the code should do.

Characterization tests can be useful when maintaining unfamiliar software. However, they do not independently establish that the documented behavior is scientifically correct.

How Should Researchers Review AI-Generated Tests?

Review should begin with the intended research procedure rather than the generated test code.

Researchers should determine which inputs and outputs matter, identify plausible failure modes, and establish expected results independently wherever feasible.

Each consequential test should then be examined for whether it checks the relevant behavior, whether the expected value is justified, and whether the assertion would fail if the implementation contained a plausible error.

For example, a test of a missing-data function should not merely confirm that it returns a dataset. It should establish which records are retained, which are excluded, and why those decisions follow the research protocol.

Researchers may use AI to propose additional cases, but should evaluate those proposals before incorporating them into the verified test suite.

Do AI-Generated Tests Replace Integration and End-to-End Testing?

No. Unit tests examine individual functions, while integration tests examine interactions between components. End-to-end tests evaluate the complete workflow from input data to final outputs.

An AI-generated scoring function might pass every unit test but receive incorrectly mapped questionnaire columns from an earlier processing step. The problem would occur at the interface between components rather than within the scoring function itself.

Researchers should therefore combine unit tests for AI-generated research functions with broader workflow checks when the code contributes to reported findings.

Testing should also be maintained as the code changes. A revision that appears to improve performance may unintentionally alter a previously verified calculation.

How Does Test Verification Support Reproducibility?

Preserving a reviewed test suite can help collaborators determine whether research code continues to behave as expected when executed in another environment.

Tests also make important computational assumptions explicit. A scoring test can document the intended handling of missing observations, while a classification test can specify whether a threshold is inclusive.

Nevertheless, a test suite cannot replace the code, input data, dependencies, or execution instructions required for reproducible AI-assisted research programming.

Researchers should preserve tests alongside identifiable code revisions and document the basis for consequential expected outcomes.

04 · A Practical Example

When AI-Generated Code and AI-Generated Tests Share the Same Error

Hypothetical Example

An Incorrect Sample Variance Calculation

A researcher asks a generative AI assistant to write a Python function for calculating sample variance. The researcher then asks the same assistant to generate unit tests for the function.

The intended calculation uses the sum of squared deviations divided by the sample size minus one. The AI mistakenly implements division by the sample size and constructs its expected test output using that same formula.

Step 1: Generate the implementation

The AI creates a function that calculates the mean, sums the squared deviations, and divides by the number of observations. The function executes without errors for the test dataset.

Step 2: Generate a test

For the observations [2, 4, 6], the AI expects a variance of approximately 2.6667 because it divides the sum of squared deviations, which is 8, by 3.

Step 3: Run the AI-generated test

The function returns approximately 2.6667, so the test passes. The test establishes consistency with the AI's expected value but does not establish that the intended sample variance was calculated.

Step 4: Establish an independent reference

The researcher checks the sample variance formula. For [2, 4, 6], the mean is 4, the sum of squared deviations is 8, and the sample variance is 8 divided by 2, giving 4.

Step 5: Add a specification-based test

The researcher adds a test requiring the function to return 4 for the reference dataset, using an appropriate numerical comparison. The original implementation fails this test.

Step 6: Correct and preserve the code

The denominator is corrected, additional boundary cases are reviewed, and the verified implementation and tests are preserved in the project's version-control history.

The AI-generated test was not useless. It accurately established what the original function returned. Its weakness was that the expected value came from the same incorrect interpretation as the implementation.

The independent reference calculation changed the test from a confirmation of existing behavior into an evaluation of the intended statistical procedure.

05 · What Researchers Often Get Wrong

Common Misconceptions About AI Testing Its Own Code

Misconception

If All AI-Generated Tests Pass, the Code Must Be Correct

Passing tests show that the implementation satisfies the assertions that were written. They do not establish that the assertions accurately represent the research requirements or cover every consequential behavior.

Misconception

Using a Different AI Model Guarantees Independent Verification

Different models may share incorrect assumptions or interpret the same ambiguous specification similarly. Independent expected outcomes and methodological justification matter more than simply using multiple models.

Misconception

High Code Coverage Proves That AI-Generated Tests Are Reliable

Coverage indicates which code was executed during testing. It does not establish whether the assertions detect incorrect calculations or inappropriate analytical assumptions.

Misconception

AI-Generated Tests Are Always Circular and Therefore Useless

AI can generate valuable tests, including cases that expose real defects. The concern is whether expected outcomes and requirements are independently justified, not whether AI contributed to writing the test syntax.

Misconception

Mutation Testing Can Prove That a Test Suite Is Scientifically Correct

Mutation testing can reveal whether tests detect selected changes to the implementation. It does not establish that the underlying specification or research method is appropriate.

Misconception

AI Can Replace Researcher Judgment by Generating More Tests

Additional tests cannot compensate for an incorrect methodological specification. Researchers must determine what the software is supposed to calculate and which outcomes constitute acceptable behavior.

06 · What This Means for You

Use AI to Expand Testing, Not to Define Correctness Without Independent Evidence

Researchers can benefit from AI-assisted testing without delegating the entire verification process to the system that generated the code.

The practical distinction is between allowing AI to help implement tests and allowing it to establish the scientific expectations against which the code is judged.

A simple decision framework

If AI generates a straightforward function with a known formula
Establish reference values independently and use AI to help translate them into executable tests.
If AI proposes additional edge cases
Review whether the cases are relevant and whether their expected outcomes follow the research specification.
If AI-generated code and tests both pass
Inspect the assertions and check whether they could detect plausible implementation errors.
If the function has no readily available exact reference output
Consider independently justified invariants, metamorphic properties, benchmark comparisons, or other suitable verification methods.
If the code affects consequential research findings
Combine reviewed unit tests with methodological inspection and broader workflow verification.

For research teams, it may be useful to record which test expectations were independently established and which were initially proposed by AI. This need not become an elaborate administrative process, but it can help prevent circular validation from being mistaken for independent evidence.

Researchers should also preserve meaningful tests with the corresponding code revision so that future changes can be evaluated against the same documented requirements.

07 · A Quick Checklist

Before Trusting Tests Generated by the Same AI That Wrote the Code

Check whether the tests provide meaningful verification:
Define the intended behavior using the research protocol, mathematical specification, or other authoritative requirements.
Verify consequential expected outputs independently of the generated implementation.
Inspect whether AI-generated assertions check actual results rather than merely successful execution or output types.
Include relevant boundary conditions, missing-data cases, and invalid inputs.
Check whether the tests would fail if a plausible calculation or classification error were introduced.
Interpret code coverage and mutation-testing results according to their limitations.
Avoid treating agreement between two AI systems as automatic independent verification.
Run integration or end-to-end checks when the function contributes to a larger analytical workflow.
Preserve reviewed tests and their documented expectations alongside the verified code.
08 · Frequently Asked Questions

Frequently Asked Questions About AI-Generated Code Tests

Can ChatGPT or another generative AI tool test code that it generated?

Yes. Generative AI can write tests and, when connected to an execution environment, may help run them. However, the tests require independent review because the model may reproduce errors or assumptions from the original implementation.

Why might AI-generated code pass AI-generated tests even when it is wrong?

The implementation and tests may share the same misunderstanding of the intended method. If an incorrect expected value is used in the test, the test can pass while confirming an erroneous calculation.

Are AI-generated unit tests reliable enough for published research?

They can contribute to a reliable verification process when researchers review their expectations, establish consequential reference results independently, and combine them with appropriate methodological and workflow checks. AI generation alone does not establish their adequacy.

Would a second AI model provide independent code verification?

It may provide an additional perspective, but model diversity does not guarantee independence. Different models can share assumptions or reproduce the same error. Independently justified expected outcomes remain important.

What is circular validation in AI-generated code testing?

Circular validation occurs when the evidence used to judge an implementation depends on the same assumptions or outputs being evaluated. For example, a test may use an expected result copied from an incorrect function rather than calculated independently.

Can mutation testing improve AI-generated tests?

Mutation testing can reveal whether a test suite detects selected changes to the code. It is useful for assessing test sensitivity but does not establish that the scientific specification or expected outcomes are correct.

Should researchers discard tests written by AI?

No. AI-generated tests can be useful, particularly for identifying edge cases and automating checks. Researchers should evaluate and improve them rather than accept or reject them solely because of their origin.

What is the strongest way to verify AI-generated research code?

Use independently established requirements and expected outcomes, review the analytical implementation, test consequential behaviors, and verify the complete workflow. The appropriate combination depends on the complexity and risks of the research software.

09 · The Bottom Line

AI Can Write Tests, but Passing Its Own Tests Is Not Independent Proof

The Bottom Line

Generative AI can generate useful tests for its own code, but those tests cannot automatically be trusted as independent verification. Shared assumptions, incorrect expected outcomes, and inadequate coverage can allow faulty research code to pass every generated test.

Researchers should use AI to assist with test development while independently establishing consequential expectations and reviewing whether the tests can detect meaningful errors. The goal is not merely to obtain passing tests, but to produce defensible evidence that the code implements the intended research procedure.

10 · Sources and Further Reading

Authoritative Resources on Software Testing and Independent Verification

11 · Cite this Guide

How to Cite This Guide

This guide is intended to be read, shared, and used in research, teaching, and academic work. If you draw on its ideas, explanations, or other content, please acknowledge the source by citing the guide. Doing so gives appropriate credit and helps your readers locate the original resource.

Has the Field Guide helped your research?

If a guide helped clarify a question, inform a research decision, or move your work forward, I would love to hear about your experience. Your story may also help other researchers discover the Field Guide.

Share Your Experience
Takes only a few minutes