Coding assistants · Research feature

New AI Framework Improves Code Accuracy Using Diverse and Reliable Tests

A study evaluates a test-centric AI framework that uses diverse and reliable tests to enhance code generation accuracy across multiple benchmarks.

Adapted from research by Chaohang Wen, Zhao Tian, Shiqi Kuang and colleagues.

arXiv preprint revision · 2026-12-03 · Attribution & reuse
In this article
Editorial illustration of two code revisions.

Editor’s introduction

The study focuses on TCG, a framework designed to improve code generation by integrating diverse and reliable tests. It compares TCG against nine baseline methods across six code generation benchmarks, measuring performance through Pass@1 metrics. Results show TCG consistently outperforms baselines in all tested settings, achieving average improvements between 6.63% and 25.59% in pass rates. The framework includes components for generating diverse tests—combining unit and property-based tests—and curating reliable ones via syntax and execution validation.

Introduction

Code generation aims to automatically produce source code that satisfies given programming specifications and serves as a fundamental capability for intelligent software development. In recent years, the rapid advancement of Large Language Models (LLMs), exemplified by Claude and DeepSeek, has led to substantial progress in code generation, offering new opportunities to reduce programming effort and improve software development efficiency. Despite these advances, however, LLMs still struggle to generate correct code for complex programming tasks. Generated programs may contain functional defects and fail to meet the quality requirements of practical software development. Therefore, improving the correctness and reliability of LLM-generated code remains a critical challenge in intelligent software development.

Despite this progress, existing test-driven code generation techniques have yet to fully exploit the potential of testing to improve code quality. We argue that the key bottlenecks extend beyond whether tests can be generated automatically: Tests must be sufficiently reliable, sufficiently diverse, and effectively leveraged throughout the code generation process. Specifically, existing approaches face three interrelated challenges. First, insufficient test correctness undermines the reliability of testing guidance. LLM-generated tests may contain syntax errors, incorrect expected outputs, or invalid program properties due to hallucinations and misunderstandings of complex specifications. Without adequate validation, such tests can provide misleading feedback, causing correct code to be rejected and defective code to be accepted. Second, insufficient test diversity limits behavioral coverage. Existing approaches often emphasize concrete input-output examples while overlooking boundary conditions, special scenarios, and general behavioral constraints. Consequently, even correct tests may fail to expose important defects, resulting in incomplete verification. Third, insufficient test utilization limits the effectiveness of test-driven code generation. Existing approaches primarily use tests for post-generation verification or rely on raw execution logs for repair, underexploiting their semantic information. Beyond pass-or-fail judgments, tests can guide requirement understanding, clarify expected behavior, and support targeted fault localization and repair. Failing to leverage this information throughout code generation limits the potential benefits of test-driven techniques.

To address these challenges, we propose TCG, a novel test-centric code generation framework that aims to improve LLM code generation by producing reliable and diverse tests and systematically integrating test information throughout the code generation process. Unlike existing approaches that primarily use tests to verify code after generation, TCG treats tests as central artifacts connecting requirement understanding, code verification, and fault repair. To this end, TCG comprises three complementary components that address test diversity, test reliability, and effective test utilization. First, to address insufficient test diversity, the Diverse Test Generation component enhances test diversity from two complementary perspectives: test dimensions and test coverage. Regarding test dimensions, the component jointly generates unit tests and property-based tests, exploiting their complementary capabilities to characterize program behavior. Regarding test coverage, it employs a test-space partitioning strategy to guide unit test generation across different categories of scenarios and a property knowledge base to guide property-based test generation toward representative behavioral constraints. Together, these strategies broaden the range of program behaviors captured by the generated tests. Second, to address insufficient test correctness, the Reliable Test Curation component progressively improves the reliability of the tests through syntax checking and execution-based semantic cross-validation. Specifically, the component first employs static parsing tools to detect syntax errors in generated tests and attempts to correct tests that fail parsing. It then exploits the complementary ways in which unit tests and property-based tests characterize program behavior to assess their reliability through an execution-based cross-validation mechanism. By selecting high-confidence tests, this component reduces the risk that unreliable tests will mislead subsequent code generation and repair. Third, to address insufficient test utilization, the Test-Centric Code Generation component integrates test information into three key stages: requirement understanding, code verification, and fault repair. Rather than restricting tests to final correctness judgments, this component uses them continuously throughout these stages, enabling tests to guide requirement interpretation, provide informative verification feedback, and support targeted fault repair. In this way, TCG fully exploits the guidance that tests can provide throughout the code generation process.

Diverse Test Generation

In LLM-based test-driven workflows, tests can be generated from natural-language requirements before a corresponding implementation or patch is available. Prior studies highlight the importance of test coverage and diversity for improving and rigorously evaluating LLM-generated code. However, existing LLM-based test generation approaches still struggle to cover targeted branches and execution paths. The generated tests tend to concentrate on a small number of typical scenarios, making it difficult to adequately cover the input space and behavioral constraints that a program may encounter. When a test suite fails to cover potential erroneous behaviors, the implementation may pass these limited tests and consequently appear correct, leading to an overestimation of code correctness. This limitation further hinders the applicability of test-driven code generation in real-world software development scenarios. To address this issue, we enhance test diversity from two complementary perspectives, i.e., test dimensions and test coverage. On the one hand, we introduce different types of tests to characterize the expected program behavior from multiple perspectives. On the other hand, we systematically design test inputs and behavioral constraints to expand the range of program behaviors covered by each test type. Specifically, we generate both unit tests and property-based tests, and design dedicated coverage enhancement strategies for each type.

Increase Test Dimensions. To increase the diversity of test dimensions, we first generate unit tests and property-based tests simultaneously based on the user requirements. The two test types are generated by a unit test agent and a property test agent, respectively. Representative test-guided code generation approaches use example-based unit tests, which specify concrete inputs and check program behavior by comparing actual outputs with expected outputs. Unit tests provide explicit and executable behavioral examples; however, their effectiveness is highly dependent on the selection of test inputs. For programs with complex logic or large input spaces, the number of possible test inputs and their combinations can be enormous, making it difficult to achieve sufficient coverage merely by enumerating concrete input-output pairs. Consequently, even if the generated implementation passes all existing unit tests, potential defects may remain undetected.

In contrast, property-based testing does not require explicitly enumerating a large number of concrete input-output pairs. Instead, it checks general properties or invariants over a range of automatically generated test inputs. For example, for a sorting algorithm, a unit test may specify a concrete input array and its expected sorted result, whereas a property-based test may define a general constraint such as preservation of array length before and after sorting for any valid input array. Thus, unit tests primarily focus on concrete behavioral instances, whereas property-based tests describe general constraints that program behavior must satisfy. These two test dimensions are inherently complementary: unit tests can validate concrete behaviors explicitly specified by the requirements, while property-based tests can explore a broader behavioral space characterized by general properties. By incorporating both test dimensions, TCG describes requirements from different levels of abstraction and perspectives, thereby improving the diversity of generated tests.

Reliable Test Curation

After generating diverse unit tests and property-based tests, we further curate the generated test cases to obtain a reliable test suite. Although LLM-based test generation methods can autonomously generate test cases from requirement descriptions, the generated tests may contain incorrect expected outputs and therefore fail to reflect the intended program behavior. This issue is particularly important in test-driven code generation, where test cases are not only used to validate the generated code but also directly participate in the feedback and decision-making process during code generation. If a test contains an incorrect expected output or an invalid behavioral constraint, the LLM may attempt to satisfy the erroneous test rather than the actual requirements, potentially accepting defective implementations or being misled during subsequent code refinement. To mitigate the negative impact of unreliable tests on code generation, we design a reliable test curation mechanism that improves the syntactic and semantic correctness of generated tests.

Improving Test Syntactic Correctness. LLM-generated test cases may contain syntax errors that prevent them from being parsed or executed. Directly using such tests in subsequent code generation not only fails to provide meaningful testing feedback but may also cause the LLM to incorrectly attribute test execution failures to defects in the target implementation, thereby interfering with the code generation process. We therefore first perform lightweight syntactic correction on the generated tests. Specifically, after generating unit tests and property-based tests, TCG invokes an AST-based parser to perform a lightweight syntax check on each test case. Tests that are successfully parsed are directly retained. For tests containing syntax errors, the parser-generated error messages are fed back to the test generation agent, which is allowed one repair attempt based on the reported error locations and error types. The repaired tests are then parsed once more and discarded if parsing still fails. Since this process relies solely on static parsing and does not require execution of the target program, it can efficiently filter syntactically invalid tests with low additional computational overhead, thereby ensuring the basic syntactic correctness of the retained tests.

Test-Centric Code Generation

Several execution-feedback-based code generation approaches execute tests after generating code and use the resulting feedback to evaluate or refine candidate implementations. When feedback is restricted to pass/fail outcomes, it does not expose the detailed semantic constraints or runtime evidence that can help diagnose failures. To fully exploit the role of testing throughout code generation, we propose a test-centric code generation strategy that transforms tests from traditional “post-generation validators” into core artifacts throughout the entire code generation process. Specifically, TCG continuously leverages test information across three stages: requirement understanding, code verification, and fault repair. In this way, tests are used not only to assess the generated code, but also to help the code agent understand requirements and the analysis agent diagnose failures and formulate repair plans.

Test-Driven Requirement Understanding. Before code generation, TCG provides the curated unit tests and property-based tests to the code agent as important supplementary information beyond the programming requirements. This enables the agent to establish a more complete and accurate understanding of the task. Programming requirements typically describe developers’ high-level intentions, such as target functionality and specific constraints. However, natural-language requirements may be incomplete, semantically ambiguous, or lacking in implementation details. In contrast, test cases provide more concrete and executable behavioral specifications. Unit tests describe the expected program behavior in specific scenarios through concrete inputs and outputs, while property-based tests further characterize constraints that the program must satisfy over a broader input space through general properties and invariants. By jointly providing the requirement description and test information, the code agent can understand the programming task from two complementary perspectives, i.e., high-level functional intent and concrete behavioral constraints. Before generating the code, the agent can therefore explicitly identify the functionality that the target program should implement and the key specification constraints that it must satisfy.

Test-Driven Code Verification. After code generation, TCG executes the target program against the curated tests to verify whether the implementation satisfies the expected behavior, while producing fine-grained test execution reports. Rather than providing the analysis agent with only shallow pass/fail feedback, TCG further collects the inputs, outputs, exceptions, stack traces, and runtime information produced during failed test executions. These details provide more comprehensive evidence for subsequent fault localization and repair. For unit tests, TCG collects different types of failure information according to the test execution results: (1) Wrong Output: For a failed test, TCG records the test input, expected output, actual output, and the specific discrepancies between them, enabling the analysis agent to explicitly identify the deviation between the generated implementation and the expected behavior. (2) Runtime Error: TCG records the exception type, error message, stack trace, error-triggering line number, and corresponding source code, thereby helping the analysis agent localize the specific execution point responsible for the program failure. (3) Timeout Error: TCG records the input that triggers the timeout and the corresponding execution time, providing evidence of potentially inefficient implementations, infinite loops, or non-terminating executions. TCG executes each property-based test on the inputs and their corresponding program-generated outputs to check whether they satisfy the predefined semantic assertions. When a property-based test fails, TCG does not merely report the test failure. Instead, it further maps the observed output discrepancy to a violation of the corresponding property, thereby helping the analysis agent understand the underlying nature of the failure. These fine-grained execution details constitute a more informative test report for subsequent fault repair.

Metrics

Pass@1 measures the functional correctness of generated code. For each problem, an evaluated method produces a single code solution. The problem is considered successfully solved if the generated code passes all golden test cases provided by the benchmark. As reported in prior studies, Pass@1 is one of the most rigorous and widely adopted evaluation metrics because it reflects the practical utility of the top-ranked result that developers are most likely to inspect and deploy. Higher Pass@1 values indicate better effectiveness.

AvgPassRatio provides a more fine-grained assessment of functional correctness. Unlike Pass@1, which treats each generated code solution as either correct or incorrect, AvgPassRatio computes the proportion of golden test cases passed by the generated code for each problem and then averages this proportion across all problems. This metric complements Pass@1 by capturing partial correctness and revealing the extent to which a method satisfies functional requirements, even when it fails on a small number of test cases. Higher AvgPassRatio values indicate better effectiveness.

Implementation Details

We evaluate TCG using three representative LLMs: DeepSeek-V3.2, an open-weight model; Gemini-2.5-Flash-Lite, a proprietary model from Google; and Claude-Opus-4.8, a proprietary model from Anthropic. These models have demonstrated strong code generation capabilities and have been widely adopted in recent studies. All models are accessed through their official APIs.

Following prior work, we set the maximum number of refinement iterations (N) to 5 for TCG and all iterative baselines. We also use consistent temperature settings across all studied techniques. During the test generation phase, we set the temperature to 0.8 to encourage semantic diversity and improve the coverage of generated tests, particularly for edge cases. During the iterative test-driven code generation phase, we set the temperature to 0 to minimize performance variance introduced by sampling randomness and ensure the stability of the refinement process. For Claude-Opus-4.8, which does not support custom temperature settings, we use its default sampling settings in both phases. To further ensure a fair comparison, all techniques use the same execution environment.

Variants

TCG consists of three main components: Diverse Test Generation, Reliable Test Curation, and Test-Centric Code Generation. To investigate the contributions of these components and their key internal strategies, we construct eight ablation variants, each of which removes or replaces a specific mechanism. For Diverse Test Generation, we design four variants: TCGwoUT and TCGwoPT remove unit tests and property-based tests, respectively, to assess the contributions of these two complementary test types to overall code generation effectiveness; TCGwoTS removes the test-space partitioning strategy used for unit test generation, while TCGwoPK removes the property knowledge base used for property-based test generation. For Reliable Test Curation, we introduce TCGwoRTC, which replaces the original test selection mechanism (i.e., execution-based cross-validation) with random selection while keeping the number of selected tests identical to that of the full TCG. For Test-Centric Code Generation, we design three variants: TCGwoRU withholds the curated tests from the code agent during requirement understanding while retaining their use in code verification and fault repair; TCGwoCV replaces the fine-grained verification feedback collected during code verification with binary execution outcomes (i.e., pass or fail); TCGwoFR replaces our test-driven fault repair strategy with a repair process based on raw test execution logs. All experiments use the same LLMs, benchmarks, effectiveness metrics, and other experimental settings as those in RQ1.