Editor’s introduction
The study focuses on CATGen, a context-aware workflow designed to improve the practical reliability of LLM-based unit test generation in real-world software projects. Researchers compared CATGen’s performance against existing LLM-based methods by measuring compilation success, structural coverage, and generation efficiency across both proprietary industrial code and the Defects4J benchmark. Results show CATGen achieves higher stability and coverage with reduced token use and generation time. The evaluation includes five repeated runs per method to ensure robustness, with statistical validation via Wilcoxon signed-rank tests. This improvement is demonstrated by comparing baseline results before and after applying CATGen’s analysis-based post-processing. Findings highlight that reliable test generation depends more on structured context and systematic engineering practices than on prompt engineering alone.
Introduction
Unit testing is a cornerstone of software quality assurance, detecting bugs early by validating the functionality of each program unit. Manually writing high-quality unit tests for the focal method (a.k.a. the method under test) can be tedious and time-consuming. To reduce this effort, numerous automated test generation methods have been developed over the past decades. Traditional methods often relied on random-based strategies, constraint-driven techniques, and search-based approaches. Deep learning-based methods have emerged, framing unit test generation as a neural machine translation problem. Despite their respective strengths, these methods still face limitations in fully understanding the code’s intent and generating syntactically correct and effective tests.
Recently, Large Language Model (LLM)-based techniques have gained significant popularity and have shown potential in automated test generation. Several LLM-based methods have been proposed, including ChatTester, ChatUniTest, HITS, TELPA and RATester. These tools empirically demonstrate the strong capability of LLMs to generate high-coverage tests over traditional ones. For instance, ChatTester, which incorporates an initial test generator and an iterative test refiner, improved the statement coverage from EvoSuite’s 68.0% to 82.3%, evaluated on their datasets. HITS is specifically devised to decompose complex focal methods into slices for LLMs, proving its superiority in generating high-coverage unit tests.
These limitations are magnified in large-scale industrial scenarios with tight release cycles, where manual correction of compilation errors is costly and undermines the productivity gains promised by automated test generation. In such settings, effective utilization of project-level context becomes critical for practical adoption at scale.
Motivated by these observations, this paper reports our experience in designing and applying a context-aware LLM-based unit test generation workflow, which we refer to as CATGen. Our goal is to distill a set of practice-driven design principles informed by repeated failure patterns observed in industrial usage, to advance the practical reliability and applicability of LLM-based unit test generation. The central insight is that compilation robustness improves when LLMs are systematically supported with explicit, structured context, instead of being asked to infer it implicitly. Specifically, CATGen is guided by three experience-derived principles centered on context acquisition and utilization via deterministic program analysis: (I) Instead of leaving LLMs to infer incomplete or missing project-level dependencies, CATGen explicitly retrieves contextual information from project structures and build configurations, ensuring that framework usage and external dependencies are accurately captured. (II) Rather than forcing LLMs to generate fragile test scaffolding code from scratch, CATGen constructs a valid test class skeleton using context-aware templates and systematic mocking strategies, allowing LLMs to focus exclusively on generating test logic. (III) To avoid costly iterative refinement, CATGen applies lightweight program analysis–based post-processing rules gained from developer feedback to deterministically repair common compilation errors and enhance test adequacy.
To demonstrate the practical value and generalizability of the proposed approach, we evaluate CATGen in both industrial and open-source environments. In the industrial setting, we construct a benchmark of eight proprietary projects from our global industrial partner, covering diverse real-world scenarios such as advanced Java features, common design patterns, and framework-intensive systems. Together with partner engineers, we curate 183 focal methods jointly prioritized for maintenance risk (evolving logic) and regression risk (failure-prone interactions); the two notions overlap in practice but are not identical sets. These methods reflect substantial industrial complexity: 57.38% involve complex dependencies, and each interacts with 3.05 external files on average. All methods originate from actively maintained production code, representing realistic testing demands rather than artificially difficult cases. Moreover, because the codebases are proprietary, the benchmark avoids potential LLM data-leakage concerns common in open-source datasets. We compare CATGen against six representative or state-of-the-art baselines, including one search-based technique and five LLM-based approaches, using compilation success rate, line coverage, branch coverage, and passing rate. The results show that CATGen consistently achieves substantially higher compilation success, with improvements ranging from 24.72%-38.05%, while also significantly improving coverage, yielding 17.27%–22.17% gains in line coverage and 15.31%–18.24% gains in branch coverage, together with reduced time and token consumption by 51.27%–69.00% in time and 66.83%–83.86% in token usage. In the open-source setting, we conduct experiments on Defects4J to examine whether the same design principles generalize beyond proprietary projects. CATGen exhibits a consistent performance trend, delivering 10.42%–14.33% improvements in compilation success over existing LLM-based approaches, while also achieving 6.11%–8.39% higher line coverage and 3.27%–10.56% higher branch coverage. Taken together, these findings highlight how practice-driven system design choices can substantially enhance the practicality of LLM-based unit test generation in industrial settings, while also demonstrating strong potential for adoption in open-source ecosystems.
Related Work
Automated unit test generation is the process of automatically creating test cases to validate code functionality. Typically, it involves analyzing the source code to identify the focal method and then generating inputs and expected outputs to verify its behavior. Over the past decade, numerous automated unit test generation approaches have been proposed to reduce the manual effort required from developers. Traditional techniques include random-based strategies, search-based approaches, and model checking. For example, EvoSuite, one of the most influential test generation techniques, employs an evolutionary algorithm to generate initial test cases and then iteratively refines them using mutation and selection strategies.
To address the readability and maintainability challenges of traditional approaches, DL-based test generation techniques have been developed by framing test generation as a neural machine translation problem. For instance, introduced ATLAS, which leverages neural machine translation to generate meaningful assert statements for test methods automatically. Similarly, proposed ATHENATEST, a BART Transformer-based approach that generates unit test cases by learning from real-world focal methods and developer-written test cases. Although DL–based techniques show promise, their effectiveness is constrained by the reliance on smaller, general-purpose pre-trained models, and they often struggle to ensure syntactic correctness and executability in complex project settings.
LLMs, trained on extensive corpora, have demonstrated impressive capabilities in generating unit tests. Several ChatGPT-based techniques have been developed to leverage its powerful language understanding and code generation skills for generating effective unit tests. For example, introduced ChatTester, which iteratively generates unit tests through interactive conversations with ChatGPT. studied GitHub Copilot for Python test generation in developer workflows, and combined search-based testing with pre-trained LLMs to escape coverage plateaus. produced HITS by decomposing the focal methods into slices and asking the LLM to generate test cases slice by slice. TELPA, RATester, and WiseUT further incorporate cross-file context, aiming to improve coverage for complex behaviors. Beyond coverage-oriented generation, RTED improves type error detection through reflective test generation and type constraints, SEGA targets business logic bugs by extracting business semantics from requirement documents, and CLAST enhances the semantic clarity of generated tests. On the other hand, conducted the first large-scale study to investigate multiple open-source LLMs, highlighting the impact of prompt design and model choice.
Despite these advances, LLM-based approaches still face significant challenges in practical settings. In particular, while many methods report improvements in coverage or test quality, they often struggle to generate tests that reliably compile and execute in real-world projects. Compared to benchmark datasets (e.g., Defects4J), industrial projects involve more complex dependencies, framework constraints, and cross-file interactions, which frequently lead to compilation failures and unstable test behavior, limiting practical usability as developers must manually fix errors before tests can be executed.
Beyond academic benchmarks, recent industrial deployments include Meta’s TestGen-LLM, Google’s BRT-Agent, and Mozilla’s BLAST. Those efforts emphasize integrating LLMs into large-scale developer workflows and reporting productivity-oriented outcomes. They seldom foreground systematic analyses of why generated tests fail to compile in framework-heavy codebases. Our experience paper complements them by studying recurring compilation failures from proprietary deployments and encoding mitigations in CATGen through structured context retrieval, deterministic scaffolding, and analysis-driven repair aimed at executability as well as coverage.
Experimental Design
To ensure that our evaluation reflects the challenges we encountered in production settings, we construct the benchmark in close collaboration with our industrial partner, capturing the failure modes observed when deploying LLM-generated tests in real repositories. In these codebases, a focal method is rarely self-contained. Its behavior is often shaped by dependency injection and configuration wiring, by contracts that are distributed across files and modules, and by framework managed execution paths where correctness depends on conventions and implicit resources. We also saw many methods with non-linear control and data flow, such as nested conditionals, early returns, and chained transformations, where meaningful branches are difficult to reach with simple happy path inputs. When this surrounding context is missing or only partially inferred, the generated tests tend to either fail to compile, set up mocks inconsistently, or run but exercise little of the intended behavior. These observations are why we treat compilation success and cost stability as first order concerns in this benchmark, not secondary metrics.
To capture these practical realities, we curate the benchmark together with engineers from our industrial partner using actively maintained and production-deployed internal Java projects. The projects span multiple architectural layers, including core service logic, data access code, configuration and wiring components, web controllers, shared utilities, and microservice infrastructure. We use project-level proportional stratified sampling to reflect both scale and diversity, and we intentionally bias selection toward difficult methods with deep call chains, cross-module interactions, and framework-managed resources.
For all LLM-based baselines, we use their publicly available open-source implementations. Because some original studies instantiated their methods with proprietary models, we standardize all LLM calls to the same set of open-source models to ensure a fair comparison. This standardization is applied consistently wherever an LLM is involved, including both unit test generation and subsequent repair steps. RATester was originally implemented for Go. To maintain a consistent Java-based evaluation environment, we follow the authors’ Java adaptation and re-implement RATester accordingly, without modifying its underlying algorithmic design.
Implementation and Environment. CATGen is implemented in Java. For program structure analysis, it uses PsiMethod from IntelliJ’s PSI to parse ASTs, enabling precise extraction of method signatures, control-flow dependencies, and inter-file relationships. The workflow depends only on AST-level facts; any conforming extractor supplying the same structural signals can substitute. The context-aware skeleton construction component employs standardized templates for JUnit 4 /5, Spock, and Spring Boot Test, with Mockito and PowerMock for mocking.
From an engineering perspective, our goal is to evaluate CATGen under practically deployable open-source LLMs rather than exhaustively benchmark all available models. We therefore select model families that (i) are publicly accessible and reproducible, (ii) provide instruction-tuned checkpoints suitable for interactive code generation, and (iii) cover both general-purpose and code-specialized variants across multiple parameter scales. We evaluate models from the Llama, DeepSeek, and Qwen families, spanning both general and code-specialized models across multiple scales: CodeLlama-7B (CL-7B), Llama3.1-8B (Lla-8B), DeepSeekCoder-6.7B-Instruct (DC-7B), DeepSeekCoder-33B-Instruct (DC-33B), DeepSeek-R1-Distill-Llama-8B (DRL-8B), DeepSeek-R1-Distill-Qwen-32B (DRQ-32B), Qwen2.5-Coder-7B-Instruct (QC-7B), Qwen2.5-Coder-32B-Instruct (QC-32B), and Qwen2.5-32B (Q-32B).
Evaluation Results
I. Effectiveness of CATGen in industrial setting. To mitigate stochasticity in LLM operations and guarantee result reliability, we independently ran all LLM-based test generation processes five times with the same configuration and used the per-method average as the final result for each metric. To assess the robustness of the observed improvements, we use Wilcoxon signed-rank tests on paired per-method outcomes after averaging the five repetitions.
Based on the RQ1 results, we select QC-32B as the representative LLM for our ablation study, given its superior line coverage and relatively high compilation success rate, which demonstrate its overall effectiveness. To mitigate random variation, we repeat each experiment five times and report the average results across all evaluation metrics.
Second, removing the static compilation error repair stage (“w/o repair”) caused a moderate drop in coverage (CovL: –8.95%, CovB: –6.22%) but a much steeper decline in CSR (–16.79%) and PR (–8.76%). This discrepancy underscores the importance of static repair in addressing syntactic and structural errors that LLMs frequently produce. As this variant retains the other components, including test enhancement, the observed decrease primarily stems from compilability issues rather than changes in the generation workflow.
Third, disabling the program analysis-based enhancement (“w/o enhancement”) resulted in a 10.51% and 9.51% drop in CovL and CovB, respectively—comparable to the loss observed when test class initialization is removed. However, CSR and PR remained largely stable (–1.96% and –0.13%), suggesting that the generated tests, although less diverse, remain syntactically and semantically valid. This validates that the enhancement module is instrumental in enriching test diversity and uncovering edge-case behaviors.
Finally, the full ablation scenario (“w/o all”)—which removes all three components—resulted in the most severe degradation. CSR and CovL dropped by 38.88% and 30.06%, respectively, roughly equating to the cumulative impact of removing individual components. These results emphasize the complementary roles of CATGen’s core modules: the test class skeleton ensures syntactic structure, static repair improves correctness and compilability, and program analysis-based enhancements enhance coverage through targeted test generation. Collectively, they form a cohesive, multi-stage framework that substantially improves both the quality and reliability of LLM-generated unit tests.
Open-Source Software Evaluation
To assess the generalizability of CATGen beyond industrial codebases, we additionally evaluate it on the widely used open-source benchmark Defects4J. Following prior studies, we select four representative projects, Chart, Lang, Time, and Math, which span diverse domains such as chart rendering, language utilities, date-time processing, and numerical computation.
We reuse the same focal-method evaluation protocol, comparison techniques, metrics, and experimental configuration as in the industrial evaluation. To ensure a controlled comparison in the OSS setting, we instantiate CATGen and all LLM-based baselines with a single underlying model, Qwen2.5-Coder-32B-Instruct (QC-32B), for all LLM invocations. All other factors, including prompts, inference settings, compilation and execution pipelines, and cost accounting, are kept identical. This setup isolates the effect of the benchmark itself, ensuring that any observed differences arise from dataset characteristics rather than changes in experimental configuration.
To further evaluate fault-detection capability, we report Mutation Score (MS)—the ratio of killed mutants to total mutants—which directly evaluates fault-detection effectiveness beyond PR. MS is reported only on the open-source benchmark; it is not reported for the industrial setting due to the proprietary nature of the dataset.
From our experience, the open-source results align with what we observed in the industrial evaluation: stabilizing the test class skeleton reduces early compilation friction, and lightweight post-processing helps recover common issues without relying on iterative LLM repair. In open-source projects where the environment is generally cleaner, these mechanisms appear to function as “reliability amplifiers”—they do not replace strong baseline capabilities, but make the generated tests more consistently executable and more thorough in structural exploration.
Interestingly, although some baselines achieve relatively high line or branch coverage, their mutation scores remain comparatively lower, suggesting that high structural coverage does not necessarily imply effective fault detection. In contrast, CATGen not only generates executable tests but also produces tests that are more effective in killing injected mutants. These results highlight the importance of complementing traditional metrics such as PR and coverage with mutation-based evaluation, and confirm that CATGen improves both executability and fault-detection effectiveness.
Discussion
II. Lessons from Replacing LLM-Based Repair with Static Analysis. Our results show that deterministic program analysis yields more effective post-processing than probabilistic, LLM-based repair. To validate this claim, we further investigate the extent to which CATGen’s program analysis-based post-processing can enhance existing baselines. Specifically, we collect the baseline results before post-processing, then substitute each baseline’s original post-processing module with CATGen’s, and re-evaluate the metrics. We use the subscript w to denote results before repair and c for results after applying CATGen’s post-processing. As in previous research questions, we use QC-32B as the underlying LLM for consistency.
III. Future Work. Currently, CATGen primarily targets Java projects; future work will extend its capabilities to support mainstream programming languages such as Python, C++, and JavaScript, enabling broader applicability across diverse software ecosystems. A key focus will be optimizing model inference efficiency by refining inference workflows and post-processing strategies to enhance scalability in large-scale industrial projects, reducing both generation time and computational overhead. To improve test robustness, we will investigate methods for generating more diverse test cases that comprehensively cover edge cases, boundary conditions, and exception scenarios. This includes developing advanced condition-decomposition algorithms and boundary-value analysis techniques to address under-tested scenarios systematically.


