Editor’s introduction
The study examines how LLM-generated unit tests are affected when prompted with buggy code. Researchers measure a ‘misguidance effect’ where such code causes models to produce tests that validate incorrect behavior, increasing the number of misguided tests while suppressing effective ones that would detect bugs. The effect is confirmed through model behavior analysis, showing a clear preference for tests that assert the erroneous behavior. The study introduces a specification-based approach that replaces buggy code with an LLM-generated specification docstring in the prompt. This method reduces misguided tests and boosts the generation of effective, bug-detecting tests. The findings apply to both buggy and bug-free code and improve performance in multi-round test generation pipelines.
Introduction
Unit testing plays a pivotal role in software quality assurance, verifying that individual components behave as expected. By detecting defects early in the development life-cycle, unit tests help reduce maintenance costs, facilitate refactoring, and enhance overall software reliability. Despite these benefits, creating manual tests remains labor-intensive and error-prone, motivating efforts to automate the process.
Recent advancements in Large Language Models (LLMs) have yielded powerful models such as GPT, DeepSeek, and Claude, which demonstrated impressive capabilities across a range of code-related tasks and prompted several recent studies focused on leveraging and evaluating their performance in automating unit test generation.
Existing studies on LLM-based unit test generation have predominantly used bug-free code as the primary prompt input and often relied on metrics like test correctness and coverage, which do not directly reflect the bug detection effectiveness of the generated tests. This common experimental design, however, fails to mirror real-world scenarios where the code under test is often buggy, which may negatively impact the effectiveness of the generated test suite. To date, only a small number of works consider buggy code as input: Abdullin et al. report on bug detection effectiveness when generating tests from buggy sources; Mathews et al. argue that buggy code can impede its own detection in automatic test generation systems; and He et al. find that, in iterative code–test generation, tests derived from buggy code generated in previous iterations may reinforce existing flaws in the code. Despite the emerging awareness, these studies neither quantify the performance degradation compared to bug-free code input nor establish the underlying source of this performance degradation.
To compute the new metric, we leverage a parallel dataset of real-world buggy code snippets and their fixed versions, allowing us to measure how test results differ for buggy and bug-free code with the same intended functionality. By generating and executing tests against both versions, we reveal a critical twofold impact: relative to the fixed counterpart, prompting LLMs with buggy code significantly increases “misguided tests” while suppressing “effective tests”—tests that successfully identify the bug. Furthermore, our correlation analysis reveals a strong positive correlation between the reduction in misguided tests and the increase in effective tests, suggesting that mitigating the misguidance effect may lead to more effective test suites. To validate the misguidance effect from a model-internal perspective, we also analyze the sequence score, a common metric for measuring an LLM’s preference among candidate texts, and demonstrate that buggy input code skews this preference toward tests asserting its erroneous behavior. We further show that this detrimental effect extends to more advanced techniques, degrading the multi-round, feedback-driven prompting pipelines common in recent test generation work.
Benchmark
In this study, we employ Defects4J, a widely used dataset containing real bugs from open-source Java projects (e.g., JFreeChart, Commons Lang). Version 3.0 of the dataset includes 854 defects (bugs) across 17 projects. Each defect comes with both a buggy and a fixed version of the code and may contain one or more buggy methods, which we refer to as focal methods. Human-written tests, including those that detect the buggy focal methods, are also provided.
Following prior work on evaluating LLM-based unit test generation, we focus test generation and evaluation on focal methods. To select focal methods, we follow the general practice of prior studies and further refine the selection based on the following criteria: (1) We include all non-private methods (public, protected, and default) in our analysis, as their accessibility from the test package makes them directly testable. (2) The focal method must exist in both the buggy and fixed versions to enable meaningful performance comparisons. Focal methods that are removed or newly introduced by the patch are excluded. (3) We only retain focal methods that trigger at least one existing human-written test in Defects4J with its buggy version, ensuring that the corresponding patch is for bug fixes rather than stylistic or performance optimizations. In total, our curated benchmark comprises 318 focal methods covering 233 defects across all 17 projects.
Metrics and Statistics
Throughout our evaluation, we treat the fixed Defects4J version as the gold standard for intended program behavior and define all test labels accordingly. Under this definition, any implementation that produces externally observable outputs that differ from the fixed version for the same inputs is not considered bug-free in our evaluation. This benchmark-specific oracle allows us to consistently label misguided, effective, and false-alarm tests across all focal methods.
For RQ2, we measure changes in both misguided and effective tests to confirm that our approach mitigates misguidance and improves bug detection. To ensure gains are not concentrated in a few focal methods, we also analyze results at the method level, reporting the number of unique methods where the LLM is misguided (at least one misguided test) and the number of unique buggy focal methods detected (at least one effective test). This verifies effectiveness across the dataset at the focal-method granularity. For the advanced analysis approach, because the model may hallucinate a non-existent “false-intent” or incorrect fix, we also report tests that assert hallucinated behavior present in neither the buggy nor the fixed version, i.e., False Positive tests. We further conduct a manual inspection to annotate whether each LLM-generated docstring (1) preserves the original bug from the buggy focal method, (2) describes the corrected behavior needed to fix the bug.
The Misguidance Effect on Test Generation
Beyond increasing misguided tests, the misguidance effect also directly undermines bug detection. For effective tests, which fail on the buggy code and pass on the fixed version, models produce only 104.15 on average (2.98%) when prompted with buggy code. When given the corresponding fixed code, this rises to 304.08 (8.51%), nearly a threefold increase. These results indicate that buggy input code not only leads to more incorrect tests, but also suppresses the generation of useful, bug-finding ones.
In real-world scenarios, the fixed version of a buggy program is unavailable for test generation. Therefore, the superior performance of tests generated from fixed code serves not as a practical baseline, but as an oracle to demonstrate the performance degradation caused by the buggy code itself. Our analysis shows that the buggy code is a primary obstacle to effective test generation, a factor that must be considered in realistic evaluations. A critical implication of these findings is that prior work that evaluated LLM-based test generation using only bug-free code likely overestimated the true bug detection capabilities of these models.
Applying Our Approach to Buggy Code
Compared to the Only Code baseline, our approach significantly improves test quality: the average number of misguided tests across all models drops from 137.69 to 113.00, a reduction of 24.69 tests (-1.15 pp). It also substantially improves bug detection, increasing the average number of effective tests from 104.15 to 186.77, an increase of 82.62 tests (+1.52 pp). These results suggest that focusing the LLM on the specification, rather than the buggy code, mitigates misguidance and yields more useful bug-finding tests.
For the No Code or Doc. baseline, both misguided and effective tests are substantially reduced compared with our approach: misguided tests drop from 113.00 to 64.38 (-1.07 pp), while effective tests drop from 186.77 to 95.38 (-1.98 pp). Moreover, a closer examination shows only 56.69% of its generated tests pass on either the buggy or fixed version, compared with 81.05% for our approach. This suggests that simply removing the code under test without providing behavioral information leaves the LLM uncertain about the expected behavior, causing many tests to align with neither the buggy nor the fixed version, making this baseline unreliable for effective test generation.
The Doc. W/ Code approach is substantially less effective than ours: on average, it produces 33.08 more misguided tests (+1.11 pp) and, crucially, 64.85 fewer effective tests (-1.33 pp). Relative to the Only Code baseline, it offers only a marginal gain, generating 17.77 more effective tests (+0.19 pp) while also producing 8.39 more misguided tests. This suggests that adding the LLM-generated specification as context is insufficient.
Impact on a Multi-Round Prompting Setup
To investigate how the misguidance effect manifests in this multi-round, iterative setting, we adopt a feedback-driven process similar to ChatTester by Yuan et al. to evaluate our proposed approach. In this setup, if a generated test fails to execute, we extract the resulting error message and append it to the original context. This augmented prompt is then resubmitted to the LLM with instructions to revise the test suite. While specific multi-round pipelines vary in architecture, this refinement loop serves as a representative baseline for our evaluation.
After three rounds of refinement, the docstring input increased the average effective test count by 35.69, more than double the 17.62 increase from the buggy code input, with similar superiority at the method level (9.85 vs. 5.69). Conversely, the misguided test count grew by only 18.08 on average with the docstring input compared to 31.77 with the buggy code input, a trend that also holds at the method level (3.38 vs. 8.62). These results confirm our approach’s effectiveness in a multi-round test generation setting.
How Does the Quality of the Docstrings Affect the Quality of Tests?
Our approach effectively reduces bug propagation into generated docstrings and recovers a substantial amount of correct behavior. Out of 318 generated docstrings per model, only 48 Gemini-generated docstrings (15.09%) and 66 Qwen-generated docstrings (20.75%) preserve the original bug. Meanwhile, 198 Gemini-generated docstrings (62.26%) and 151 Qwen-generated docstrings (47.48%) recover the correct behavior needed to fix the bug of the focal method.
Docstrings without buggy behavior lead to significantly fewer misguided test suites, while docstrings that recover correct behavior contribute to substantially more detected bugs. For Gemini, the 270 bug-free docstrings account for only 19/43 misguided focal methods, while the 48 bug-preserving docstrings account for 24/43; the 198 docstrings that recover the correct behavior contribute 80/100 detected bugs, compared with 20/100 from the remaining 120 docstrings. Similarly for Qwen: the 252 bug-free docstrings account for 17/40 misguided focal methods versus 23/40 for the 66 bug-preserving docstrings, and the 151 docstrings that recover the correct behavior contribute 55/86 detected bugs versus 31/86 from the remaining 167 docstrings.
External Validity
Threats to external validity concern the generalizability of our findings. Our study relies on the Defects4J benchmark, a common choice in prior work. We used a diverse set of 318 focal methods that span all 17 projects in Defects4J, ensuring a reasonable breadth of evaluation data. Additionally, our evaluation of 11 SOTA LLMs, representing the most advanced models at the time of our study, supports the generalizability of our results. Nevertheless, Defects4J may not fully capture two real-world scenarios. First, in proprietary or highly domain-specific systems, LLMs may lack sufficient domain knowledge or context needed to infer intended behavior, potentially producing hallucinated “false-intent” or incorrect bug fixes. Second, for deeply stateful or dependency-rich code, a method-level docstring may omit important class, state, or dependency information, potentially leading to unusable tests or shallower coverage. Although our prompt includes surrounding class context following Yang et al. and constructors of user-defined object types, this context may still be insufficient for large-scale, dependency-rich projects.
Construct Validity
Threats to construct validity in our study stem from three main sources. First, to mitigate the inherent randomness of LLMs, we set the generation temperature to 0, where possible, to promote deterministic outputs. Second, data contamination is a potential threat, as the manually written tests in Defects4J may have been part of the models’ training data. However, our proposed docstring-based approach can be seen as a form of paraphrasing, a technique commonly used to reduce the impact of data contamination. Moreover, this prompting yielded a significant improvement across all models rather than a drop, suggesting that the LLMs are not simply recalling memorized tests but operating on the information provided by the specifications. Third, our advanced-prompt approach may introduce hallucinated behavior that is then asserted by generated tests. We assess this risk by measuring “False Positive” tests that fail on both the buggy and fixed versions for buggy code, as well as false-alarm tests that fail on correct implementations for bug-free code. In both settings, we observe only minor increases compared with the source-code baselines, suggesting that this risk is not substantially elevated.
Related Work
Traditional automatic unit test generation prior to LLMs relied on techniques like symbolic execution, search-based algorithms, and model checking. However, these techniques often produce tests with low maintainability and readability compared to human-written ones, making it challenging for human developers to gain useful knowledge from them.
Subsequently, transformer-based models demonstrated promising results in various code-related tasks, including code generation, automated program repair, and code translation. Early efforts to apply these models to unit test generation treated the task as a sequence-to-sequence problem—akin to machine translation—using smaller-scale architectures such as BART, PLBART, and CodeT5 trained with code–test pairs. For instance, Tufano et al. introduced a BART-based model trained specifically for unit test generation; Alagarsamy et al. proposed A3Test, a PLBART-based approach that augments assertions to improve test quality; and Shin et al. applied domain adaptation to CodeT5 to enhance unit test generation.
The emergence of large decoder-only LLMs, like GPT, capable of scaling to hundreds of billions of parameters, has enabled more natural and maintainable test generation. One of the earliest specialized approaches, CAT-LM, trained a GPT-style model on aligned code–test data. Larger models such as GPT-4, Claude, and Llama, while not explicitly trained for unit test generation, can still produce meaningful test cases when guided by well-crafted prompt instructions. Recent work has explored various prompting strategies to improve test correctness and coverage with these models. Complementary studies also investigated how different fine-tuning methods further enhance LLMs’ capability in unit test generation.
While a significant number of prior studies have evaluated LLM-generated unit tests primarily in terms of test correctness and coverage, their core function—bug detection—has received relatively limited attention. Recent research has begun to fill this gap by directly assessing and improving the bug detection capability of LLMs. However, these studies typically use correct code as input, overlooking the real-world scenarios where code under test can often be buggy.
Conclusion and Future Work
In this paper, we provide a large-scale quantitative study of the misguidance effect in LLM-generated tests: a phenomenon where buggy code causes LLMs to misinterpret erroneous behavior as intended functionality. Using a new metric we introduce, we empirically demonstrate the effect’s severe, twofold impact: it increases the generation of “misguided tests” that validate the bug while simultaneously suppressing “effective tests” that would detect it. Furthermore, we confirm this effect from a model-internal perspective by showing that buggy code skews the model’s preferences toward “misguided tests” that assert its erroneous behavior.
To address this, we propose and validate a specification-based approach that decouples test generation from the potentially flawed implementation by using a specification constructed from the code under test as the sole behavioral input. Our experiments show that even a simple, LLM-generated docstring significantly mitigates the misguidance effect and improves bug detection. We further demonstrate that this method can be enhanced with reasoning-based code-intent analysis and serves as a more effective foundation for a multi-round, interactive prompting workflow. Finally, our approach applies to both buggy and bug-free code, achieving comparable levels of compilation failures, false-alarm tests, and test coverage on the latter.
Our work underscores the necessity of addressing the misguidance effect and demonstrates that shifting the focus from faulty implementations to intended specifications is a robust and effective path forward for LLM-based software testing. Future work includes developing more robust specification-generation approaches that reliably infer intended behavior in large-scale or domain-specific projects, potentially by combining multi-agent LLM reasoning with behavioral information from static program analysis; exploring specification formats beyond natural language, such as UML diagrams or formal specifications; and comparing LLM-generated specifications with high-quality, human-written ones to evaluate their effectiveness in mitigating misguidance and to understand the upper bound of this approach.


