Code evaluation · Research feature

Improving LLM-Driven Test Generation by Learning from Mocking Information

A new study evaluates how using existing mock test data enhances AI-generated software tests, finding improved coverage and fault detection.

Adapted from research by Jamie Lee, Flynn Teh, Hengcheng Zhu and colleagues.

arXiv preprint revision · 2026-04-21 · Attribution & reuse
In this article
Editorial illustration of aperture mechanism.

Editor’s introduction

The study examines MockMill, an LLM-based method that uses mocking information from developer-written tests to guide test generation. It compares generated tests against existing project tests and baseline approaches like Randoop and vanilla LLM methods. Results show MockMill identifies new lines of code and kills mutants missed by other methods, indicating that mock data provides useful contextual cues. The findings suggest that leveraging developer-defined mocks helps AI generate more realistic and effective tests. The evaluation was conducted across 10 open-source Java classes from six projects using four LLMs, with each experiment repeated ten times to ensure consistency. The evidence supports that mock-informed generation consistently detects faults not found by baseline techniques, though the study offers only preliminary evidence on the broader impact of such approaches in real-world software development.

Introduction

Software underpins modern life, making rigorous testing essential to ensure correctness. Yet writing high-quality tests is labor-intensive, motivating decades of automated test generation research. Long-standing approaches range from random testing to search-based methods. Recently, the emergence of Large Language Models (LLMs) has opened a new frontier for automated test generation. LLMs, trained on vast code corpora, can produce useful tests, often with minimal human guidance. This capability has sparked interest in LLM-based testing. However, while the results of LLM-driven test generation are highly promising, many aspects of LLM-based test generation remain underexplored, particularly the impact of providing specific auxiliary artifacts beyond the class under test.

In this paper, we explore how to improve LLM-driven test generation by leveraging test doubles (or more informally also referred to as mocks). Test doubles are test artifacts commonly used to manage the complexity of interacting components during testing. They are lightweight stand-in objects that mimic real components, allowing developers to isolate the software under test from its dependencies, also referred to as mocked components. Test doubles can be configured to return predefined responses for specific inputs (stubbings) or to check expected interactions (verify operations). Through them, developers implicitly specify how dependent components should behave. Test doubles are central to modern software testing, and studies across programming languages show that stubbing and verify operations are widely used in both industry and open-source software. Tests generated from test double information can help verify dependent components when they are part of the software system.

Existing LLM-based approaches typically generate tests using the code under test and its associated documentation or comments, making the rich usage patterns and expected behaviors encoded in test doubles an untapped resource for improving automated test generation. To bridge this gap, we introduce MockMill, an LLM-based approach that leverages the mocking information from an existing test suite to generate new tests. Given the software under test and its test suite as inputs, MockMill generates tests for those components that are replaced by test doubles in existing tests. The approach starts by automatically extracting mocking information from the test suite via static analysis. MockMill then employs an LLM-guided approach to generate tests for targeted components. The approach integrates a generation-and-repair loop: the extracted mock information is incorporated into the LLM input to generate candidate tests, and any compilation or runtime issues in the tests are iteratively fixed via LLM-based corrections. By guiding an LLM with this existing, developer-defined information, MockMill produces tests that align with the behavioral expectations already encoded in the test suite.

Test Generation

The Test Generation phase constructs LLM prompts for automated test creation based on the target component and the extracted mock information. In this phase, a structured prompt is assembled that provides the LLM with (i) explicit test generation instructions, (ii) the complete source code of the target component (e.g., the source code of the target class), and (iii) the data associated with the relevant stubbings and verify operations. Including the full class source code enables the LLM to reason about the implementation context, dependencies, and behaviors, thereby reducing the likelihood of incorrect assumptions or hallucinations.

Prompt design: The test generation prompt targets mutation-based adequacy, as mutation coverage is widely recognized as one of the most comprehensive test adequacy criteria. The prompt instructs the LLM to (i) use exact values from stubbings and verify operations; (ii) create precise assertions that fail under realistic mutations (bugs); (iii) test both true and false execution paths and boundary conditions derived from mocking information; and (iv) generate tests that instantiate and exercise real objects of the CUT rather than substituting them with test doubles.

Baselines. The approach also uses a few-shot prompting strategy and provides two examples for the requested task. The examples are based on simple, self-contained Java classes along with corresponding structured mock and stub data extracted from representative tests. This data captures real interaction patterns that reflect how the CUT is used. The examples then include executable unit tests that instantiate the CUT, exercise its behavior, and assert on expected outputs. We intentionally designed the two few-shot examples to be domain-agnostic (and are not based on any of the projects considered in the evaluation). The prompt also does not target or identify specific mutants to kill. It encourages the LLM to produce tests that satisfy mutation-based adequacy criteria in a general sense. Finally, the prompt specifies the required output format, directing the LLM to produce a compilable test file that includes all necessary package declarations and import statements.

Post-Generation Repair

After generation, MockMill iteratively compiles and repairs tests, following prior LLM-driven test generation. If compilation fails, the resulting error messages are passed to the LLM with targeted repair instructions to produce a corrected test file. This cycle repeats until the tests compile successfully or the retry limit is reached. The same iterative process applies to runtime failures. Once compilation succeeds, MockMill executes the tests and, upon failure, provides the error logs to the LLM for correction. This loop continues until all tests pass or the maximum retry limit is reached.

This design assumes a regression testing scenario, where failing generated tests are attributed to issues in the tests themselves rather than bugs in the target component. By default, MockMill treats failures as test issues (e.g., a component not properly set up) and attempts to fix them. Users can also manually inspect failing tests if they suspect the failure originates from bugs in the target component. The final test suite is executed for coverage and mutation analysis to evaluate adequacy and fault-detection capability.

Prompt design: The repair prompt includes the error message along with the source code of the target component and the generated tests. It explicitly forbids explanations or comments and requires the LLM to use a significant change in approach on repeated attempts. These constraints reduce verbosity and focus the LLM on producing concise and executable tests.

Methodology

Baselines. To evaluate the complementarity of MockMill, we considered three baselines: an LLM-based test generation approach (which we refer to as LLM), Randoop (i.e., an approach based on random testing), and the developer-written tests. LLM uses the same prompt and few-shot examples as MockMill but omits mock and stub information. This configuration allows for a controlled comparison that isolates the relative contributions of mock information in the LLM-driven test generation process. Although Evosuite is generally more effective than Randoop, we used Randoop because it provided better support for the recent Java versions associated with the projects considered. Across projects, developer-written tests were found for only five CUTs.

Models. In RQ1, we evaluated MockMill in combination with four LLMs. Table II lists the models we used and the token costs used at the time we ran the experiments (September 2025). At that time, GPT–4o Mini was recognized as a lightweight, cost-efficient model, GPT–5 Mini and GPT–5 represented newer reasoning-capable variants, and Claude Sonnet 4.5 provided a cross-provider comparison. All models were used with default parameters. In RQ2, we used GPT–5 Mini, as it was a top-performing model in RQ1 and it was cheaper than the other top-performing model Claude Sonnet 4.5. Selecting this model allowed us to focus the comparison on the relative benefits of MockMill while controlling experimental costs and maintaining consistency across runs.

Metrics. We considered four classes of metrics: generation, compilation, execution, and quality. In terms of generation, we report the average number of TeSt generaTed per CUTs (TST). Compilation metrics assess whether MockMill produces tests that can be built automatically. These metrics capture feasibility boundaries: percentage of tests that Compiles on the First Try (CFT) demonstrates immediate usability, while percentage of tests that Compiles EVentually (CEV) reflects the effectiveness of MockMill’s repair loop. Execution metrics measure how many executable tests MockMill generates. TestS Passed (TSP) reports the percentage of tests that pass. Quality metrics assess how effectively the generated tests detect faults and exercise code, since quantity and executability alone do not ensure usefulness. We report the minimum (MIN), median (MED), maximum (MAX), and standard deviation (STDEV) of mutation score (fault detection) and line coverage (structural coverage). We use PIT (with all mutations enabled) and JaCoCo to measure mutation score and line coverage, respectively. For fault detection, we also report Unique Mutations Killed, which isolates the exclusive contributions of a given technique, revealing complementarity that aggregate percentages can hide. For structural coverage, Unique Lines Covered highlights lines reached only by a technique. Together, these metrics provide a nuanced picture, as it is possible to identify when approaches add non-overlapping value relative to others.

RQ1: Effectiveness

– To what extent can MockMill generate effective tests? Table III reports the results associated with RQ1. The average number of generated tests (TST) varies markedly across models. While GPT–4o Mini, GPT–5 Mini, and GPT–5 generate between 8.5 and 13.2 tests on average, Claude Sonnet 4.5 produces a much larger number of tests (45.7 on average). However, this larger test volume does not translate into clearly better quality than other models in terms of median mutation score and line coverage.

MockMill is generally successful at producing compilable tests across all considered models. Although first-try compilation (CFT) varies across models, eventual compilation (CEV) is consistently high, ranging from 92% for GPT–4o Mini to 100% for the remainder. This result indicates that the generation-and-repair loop of MockMill is effective at overcoming a substantial portion of the issues that arise during initial test generation.

The execution results further support the effectiveness of MockMill. In terms of pass rate, all models except GPT–4o Mini achieve near-perfect results, with TSP values between 98.6% and 99.7%. Taken together, these results indicate that MockMill is able to generate not only compilable but also executable tests with high reliability, especially when paired with GPT–5 Mini, GPT–5, or Claude Sonnet 4.5.

RQ2: Complementarity – To what extent do tests generated by MockMill complement those generated by baseline approaches and existing tests?

Across CUTs, MockMill achieves higher unique mutation kill rates than both LLM and Randoop only (shown in Table IV). CAS and RRA are prime examples of this, showing a MockMill detection rate of 24.56% and 25.64%, compared to LLM ( 0-12.82%). MockMill achieves a strictly higher unique mutation killed rate than LLM for 40% of CUTs and Randoop for 50% of CUTs. Randoop rarely kills any unique mutations, with killing 2.56% only on RRA. For MAS, MUT, QPC, and SMS, the table shows 0% across all approaches, indicating that MockMill performs similarly across all cases. This suggests that mock information generally helps identify unique mutation cases missed by other tools. The low Randoop performance indicates that a simple traditional test generation approach might struggle to detect nuanced faults without the contextual and semantic reasoning available to LLMs.

Unique line coverage is generally low across all CUTs, with only minor contributions from MockMill (e.g., 2.61% for RRA, 1.56% for MQS, and 1.79% for URE) and one case for Randoop (2.61% for RRA). Mock information yields a small but measurable advantage, exposing a few additional lines not reached by other techniques. However, its overall impact on coverage is less pronounced than on mutant detection.

Developer tests contribute the fewest unique mutations (2.56% for RRA, none elsewhere), indicating that LLM-generated tests can reveal faults missed by human developers. Mock information enhances this advantage by improving fault detection diversity. For line coverage, differences are minor. MockMill-generated tests again show the highest exclusive coverage (e.g., 2.61% for RRA, 1.56% for MQS), while no-mock and developer tests contribute little additional coverage. Although the differences are minor, there is evidence that mock information can help LLMs reach certain lines missed by LLM, Randoop, and developer tests.

Traditional Test Generation Techniques. Random testing and search-based software testing reduce manual effort by automatically producing tests to maximize structural coverage. Similar to MockMill, these techniques leverage information in source code to enhance test generation. MSeqGen mines method call sequences from code repository to achieve higher coverage. Fraser and Zeller mine object usage patterns from existing code to generate meaningful tests. Our work complements them by utilizing mocking information to guide test generation toward better tests.

Automated Test Generation with LLMs. LLM-based approaches generate unit tests via prompt engineering and structured context. Studies on zero-shot, few-shot, and Chain-of-Thought prompting show that richer, code-aware inputs (e.g., signatures, existing tests, stack traces) outperform plain natural language prompts. Accordingly, pipelines typically collect project context, query an LLM, and iteratively compile/execute and repair failing outputs. Similar to prior work, MockMill relies on prompt design and post-processing. However, unlike approaches that build context solely from source code and project metadata, MockMill also leverages developer-written mocks and stubs as structured input to guide the LLM in generating realistic tests for mocked and stubbed classes. Although prior tools may generate tests with test doubles, none explicitly exploit existing mocking information to guide test generation. To the best of our knowledge, MockMill is the first to do so.

Test Doubles in Software Testing. Recent work has introduced tools that analyze, generate, or refactor mocks and stubs to improve testing quality and maintainability. MockSniffer characterizes recommends mocking decisions. Empirical studies on mock assertions suggest that mocks capture developers’ behavioral intent and domain knowledge. MockMill directly utilize this encoded intent to inform LLM-driven test generation. StubCoder generates and repairs stub code via evolutionary search to keep tests passing as production code evolves. RICK records production executions and generates tests that mimic observed behavior using test doubles. ARUS improves maintainability by detecting and removing unnecessary stubbings. Compared with these approaches, MockMill does not aim to generate or improve test doubles but instead leverages the behavioral information already encoded in them to guide LLMs in generating new tests.

Conclusions and Future Work

This paper introduced MockMill, the first LLM-based test generation approach that leverages developer-written mocking information to guide test creation. MockMill generates tests that uncover lines of code and mutants missed by baseline approaches, showing that mock information provides valuable contextual cues for producing realistic and useful tests. The approach complements developer-written suites, traditional tools such as Randoop, and an vanilla LLM-based approach. The cost overhead of 5–15% with respect to the LLM baseline considered is acceptable given the corresponding improvements in test quality and fault detection capability.

Our findings suggest that future LLM-driven test generation should incorporate available mocking information as contextual guidance to produce more comprehensive and realistic tests. Rather than replacing existing methods, mock-informed generation should complement them within a holistic LLM-based testing framework that integrates both mock-informed and non–mock-informed prompts.

As the first work of its kind, MockMill opens several promising research directions. Future work includes ablation studies to assess the relative impact of mocking information, automatic extraction of project-specific few-shot examples to improve performance, dynamic collection of mocking data to capture richer behaviors, and establishing traceability links between test doubles and generated tests to better understand their influence on test creation.