Code evaluation · Research feature

Call-Chain-Aware LLM-Based Test Generation for Java Projects

A new AI approach enhances unit test creation for Java software by incorporating call-chain and dependency contexts into test generation prompts.

Adapted from research by Guancheng Wang, Qinghua Xu, Lionel C. Briand and colleagues.

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

Editor’s introduction

The study evaluates CAT, a call-chain-aware LLM-based test generation method for Java projects, which integrates caller-callee relationships, object constructors, and third-party dependencies into prompts through static analysis. The researchers compare CAT to PANTA, a state-of-the-art LLM-based method, and EvoSuite, a search-based tool, on the Defects4J benchmark and four real-world GitHub projects released after the LLM’s cut-off date. Results show CAT achieves higher line, branch, and mutation coverage across all projects compared to both methods. On real-world projects, CAT achieves the highest average coverage among the evaluated approaches.

Introduction

Unit tests play a fundamental role in ensuring software quality and reliability. However, writing high-quality unit tests remains labor-intensive and requires substantial domain knowledge, posing a long-standing challenge for software engineers. To mitigate this burden, a variety of automated test generation techniques have been proposed, including random testing (e.g., Randoop ), search-based testing (e.g., EvoSuite ), and symbolic execution–based approaches (e.g., KLEE and Pex ). These techniques have proven effective at detecting critical defects by systematically exploring program behaviour. These techniques differ in how they obtain test inputs. Random testing extends random sequences of method calls using execution feedback; search-based testing evolves test suites towards coverage goals; and symbolic execution derives inputs by solving path constraints. Their test oracles are typically inferred from observed executions or from generic properties (e.g., crashes and contracts). KLEE and Pex target C and.NET programs, respectively, whereas Randoop and EvoSuite focus on unit test generation for Java—the setting studied in this paper. We include EvoSuite as a non-LLM baseline in our evaluation (Section 4) because it is commonly used as the reference non-LLM tool in recent studies of LLM-based test generation and has outperformed Randoop in coverage, mutation score, and real-fault detection. More recently, advances in machine learning and large language models (LLMs) have further pushed the frontier of automated test generation. LLM-based approaches leverage learned programming knowledge and contextual reasoning to generate readable, functional test cases, significantly improving both the automation and effectiveness of testing. Despite these advances, most existing work focuses on method-level or class-level test generation, which typically considers only the program logic within a single module. In contrast, project-level test generation, which must account for complex interprocedural dependencies, execution contexts, and interactions across multiple modules, remains largely underexplored and challenging. This gap limits the applicability of current techniques in large-scale software systems.

This observation suggests that the key difficulty lies not in identifying uncovered code locations but in constructing valid execution contexts, such as cross-class dependency setups, object initializations, and call sequences required to invoke the focal method. However, existing path-guided approaches provide limited insight into how such contexts are formed, as they focus primarily on uncovered code feedback without modeling dependency structures or object initialization processes. We further observe that the required execution contexts are inherently encoded in the call chains leading to the focal method, together with the constructors of the involved classes. These call chains capture how objects are created, how external dependencies are invoked, and the order in which different components interact. Therefore, we propose CAT, built on a dedicated static analysis framework that systematically captures relevant execution contexts. Specifically, CAT extracts call-chain information and associated initialization contexts, including caller-callee relationships, object constructions, and third-party dependencies, and explicitly provides the LLM with such rich project-level context, enabling it to generate valid tests even for methods with complex inter-module and third-party dependencies.

Motivating Example

The first two focal methods shown in Listing 1, hasXMLFormat and hasFormat, from the XmlFactory class in the JacksonXml-5f project of the Defects4J dataset, illustrate a common scenario in real-world codebases. Both their input type InputAccessor and return type MatchStrength are defined outside XmlFactory, introducing dependencies on external classes and requiring non-trivial object construction and cross-class interaction to correctly invoke these methods. Such scenarios highlight a fundamental challenge for coverage-driven test generation approaches. Since these methods depend on externally defined types and initialization logic, simply guiding test generation toward uncovered code regions is insufficient. In particular, when the generation process is primarily driven by coverage feedback, it tends to focus on exploring new execution paths without explicitly reasoning about how required objects are constructed or how inter-class dependencies are resolved. As a result, the generated tests often fail to establish valid execution contexts for methods with complex dependencies, limiting their ability to reach and execute the target methods effectively.

Our approach addresses both limitations through a dedicated static analysis framework. First, we generate tests one focal method at a time, which avoids ambiguity caused by overloaded methods. Second, we systematically extract relevant execution contexts, including both call-chain information and external class dependencies, via static analysis (see Listings 2 and 3).

We illustrate our approach using the focal method hasFormat as an example. Listing 2 shows the call-chain context of hasFormat in a simplified form. Each block gives the declaring class, the method with its parameter types and, after the arrow, its return type. For brevity, we list each indirect call chain from its public entry method up to the last method before the focal method; the final call to the focal method (which ends every chain) is omitted.

The first block is such an indirect chain. DataFormatDetector.findFormat(byte) wraps the given bytes in an InputAccessor and passes it to the private helper _findFormat, which calls hasFormat on the JsonFactory instances registered in the detector until one of them reports a sufficiently strong match. Since XmlFactory extends JsonFactory and overrides hasFormat, CHA links this call to the focal method, which is reached at run time when the detector holds an XmlFactory. The private helper cannot be called from a test and is removed by the visibility filter (Section 3.2.3); thus, findFormat is both the entry method and the last method before the focal method. The second block is the focal method itself, which, being public, can also be invoked directly.

Call Graph Construction and Metadata Collection

In the second phase, we collect a set of metadata maps, including the class visibility map classVis, the method visibility map methodVis, the constructor map ctors, and the implementation map impls. The visibility maps record whether each class or method is publicly accessible, which is essential for identifying valid invocation entry points and feasible call paths. The constructor map stores public constructors for each class, enabling object instantiation during test generation. The implementation map maps supertypes (including superclasses and interfaces) to their public concrete implementations, facilitating the resolution of virtual and interface dispatch during call graph construction.

Process

In addition to coverage and mutation score, we report the total number of LLM tokens consumed, end-to-end test generation time, the number of retained test methods, and the proportion of retained test methods that use a mocking framework. The total token consumption includes both input and output tokens across all LLM calls made during test generation and repair. End-to-end time measures the wall-clock time from the first LLM invocation to the final test suite, including LLM inference, test repair, compilation, and test execution. It excludes the static-analysis phase used to construct call-chain and dependency contexts, since this analysis runs offline as a one-time preprocessing step and its results can be reused throughout test generation. The number of retained tests is the number of test methods remaining in the final test suite after all generation and repair iterations. CAT retains every test that compiles and passes, including tests that do not increase coverage, and does not remove duplicated tests; PANTA likewise adds every passing test to its test file. The reported number of retained tests may therefore include duplicated tests, which we did not measure; since a duplicated test executes the same code and checks the same behavior as the test it duplicates, it can inflate the test count but not coverage or the mutation score. To measure the use of mocking, we inspect each retained test method and classify it as using mocking if the method itself, or its test setup required for execution, invokes APIs from the adopted mocking framework (e.g., Mockito). We then compute the mocking rate as the number of retained test methods using mocking divided by the total number of retained test methods. We apply the same metrics and measurement procedures to RQ3. To further analyze API hallucinations, we examined the compilation diagnostics and test execution results of all tests generated by CAT on the Defects4J projects, checked the referenced program elements against the project source code, classified the identified hallucinations into two main categories reported in detailed results, and calculated the percentage of all generated tests affected by each category.

In RQ1 and RQ3, we additionally compare against EvoSuite using a strong configuration informed by prior studies. Specifically, we use DynaMOSA as the search algorithm, following its empirical evaluation in prior work and its adoption in subsequent EvoSuite-based studies. We further enable private-API access through reflection and functional mocking, which have been shown to facilitate constructing program states that are difficult to reach through public APIs alone, and we use a mutation-based strategy for assertion generation. We allocate a generous search budget of 900 seconds per run and focal class, substantially exceeding EvoSuite’s default search budget of 60 seconds and the budgets commonly adopted in prior studies. EvoSuite 1.2.0 is executed under the same Java/JDK environment as the other approaches, while the remaining parameters retain their default settings. Since its search is randomized, we run it three times per focal class with different random seeds and report the average line coverage, branch coverage, and mutation score over the three runs. We do not include EvoSuite in the comparison of LLM token consumption, end-to-end generation time, mocking rate, or the number of retained tests. Token consumption is not applicable because EvoSuite does not rely on LLM inference. Its generation time is determined by a fixed search budget and is therefore not directly comparable to the iterative LLM-based generation process; moreover, we intentionally provide EvoSuite with a substantially larger budget of 900 seconds to avoid disadvantaging it. Similarly, EvoSuite incorporates functional mocking as an intrinsic test-generation mechanism, making its use of mocks conceptually different from mocks generated by the LLM-based approaches. We therefore use EvoSuite primarily as a reference baseline for comparing the effectiveness of the generated test suites: line coverage, branch coverage, and mutation score.

Comparison between CAT and baselines

On average, CAT surpasses PANTAtb and PANTA by 8.94 and 12.52 pp (12.23% and 18.02%) in line coverage, and by 9.61 and 12.97 pp (15.11% and 21.52%) in branch coverage, respectively. Across most projects, CAT outperforms both baselines, highlighting the effectiveness of incorporating call-chain extraction for call context and dependency resolution for dependency context in prompts for project-level test generation. Two exceptions appear: JacksonXml, where CAT does not achieve the highest line coverage, and Codec, where the same holds for branch coverage.

Compared with EvoSuite, CAT achieves higher line coverage on all 14 projects, by 9.67 pp (13.37%) on average, whereas its average branch coverage is only 4.17 pp (6.04%) higher, with EvoSuite achieving the highest branch coverage on five projects (JacksonXml, JacksonCore, Jsoup, Time, and Lang). This is consistent with EvoSuite’s search, which directly targets individual branches as coverage goals.

For the JacksonXml project, CAT performs slightly worse than PANTAtb by 0.67 pp (1.03%) in line coverage, while achieving 4.20 pp (7.76%) higher branch coverage. This suggests that although the richer call-chain and dependency context provided by CAT is particularly effective for exploring diverse execution branches, the uncovered-path information used by PANTAtb still offers valuable guidance on input constraints and path-specific conditions, which can help cover certain lines of code. In other words, while CAT improves overall branch exploration by addressing dependency issues through call-chain graph information in the prompts, challenges related to precise input construction and oracle generation still remain. For example, many failures stem from expected values that do not match the current implementation’s output and from incorrectly generated inputs.

For the Codec project, CAT achieves higher line coverage than PANTAtb but slightly lower branch coverage. In particular, CAT improves line coverage by 3.99 pp (4.85%), while reducing branch coverage by 3.99 pp (4.91%) compared to PANTAtb. This result reflects the characteristics of the Codec project and the different mechanisms of the two approaches. Compared to other subjects, Codec contains a higher proportion of branch-intensive, rule-based logic, where execution paths are heavily determined by fine-grained input conditions. In such a setting, CAT benefits from call-chain-guided execution context construction, which helps resolve cross-class dependencies and improves reachability of executable code, leading to higher line coverage.

CAT Performance on Unseen Projects

Compared with RQ1, CAT achieves 82.01% line coverage and 73.23% branch coverage on Defects4J, while reaching 67.70% and 58.42% on unseen projects. This performance drop is likely attributable to the increased complexity of the unseen projects, which are more recent and exhibit a higher average maximum cyclomatic complexity (CYCmax) than the Defects4J subjects (33 vs. 27), and may also be influenced by potential data leakage effects in the Defects4J benchmark. Such projects often involve deeper call chains, richer third-party dependencies, and more intricate object initialization patterns, all of which make it more challenging to construct valid execution contexts.

Nevertheless, CAT consistently outperforms both LLM-based baselines across all unseen projects, confirming that the proposed call-chain- and dependency-aware context modeling strategy generalizes effectively beyond benchmark-specific settings. Importantly, because these projects postdate the employed LLM’s cut-off, the observed gains cannot be explained by memorization and instead indicate genuine improvements in context construction and test generation.

At the same time, the lower absolute coverage on unseen projects suggests that project-level test generation for dependency-rich systems remains a challenging problem. Future work could explore more advanced techniques for modeling dynamic dependencies, improving context selection under long call chains, and integrating complementary signals beyond static call-chain and dependency information to further improve generalization.

Conclusion

In this paper, we presented CAT, an LLM-based test generation approach built on a dedicated static analysis framework that systematically captures execution contexts. By explicitly modeling call-chain and dependency contexts—including caller–callee relationships, object constructors, and third-party dependencies—CAT helps the LLM construct executable and semantically valid contexts for project-level test generation. Our evaluation shows that CAT on average outperforms state-of-the-art approaches on both Defects4J (a widely used benchmark in prior work) and real-world GitHub projects released after the employed LLM’s cut-off date.

We also find that naively combining execution-path information with other signals does not necessarily improve performance, suggesting that effectively integrating complementary sources of information remains challenging. Our ablation study further shows that both call-chain and dependency contexts are essential components of CAT.

Overall, our findings highlight the importance of modeling call-chain-aware execution contexts in LLM-based test generation. We suggest that future work explore more principled methods for integrating heterogeneous signals (e.g., execution paths and input–output relationships) to better support automated test generation. Future work could also improve the precision and completeness of the extracted contexts. For example, propagating receiver types along call chains could prune incompatible dispatch targets, and comparing extracted paths with call edges observed during test execution could quantify how many relevant paths are missed. Since generated tests reside in the focal class’s package, we could admit package-private and protected methods in that package as entry points, and invoke package-private and protected focal methods directly; this would require adapting the visibility filter, the initialization context, and the generation prompt.

In addition, a finer-grained analysis of test fixing across iterations, together with more effective fixing strategies, could improve the recovery of failed generated tests. CAT could also start from an existing test suite (e.g., one generated by EvoSuite) and generate tests only for code left uncovered, potentially reducing the time and cost of test generation. Like the compared approaches, CAT generates regression tests whose assertions reflect current program behavior; combining CAT with oracle generation techniques could yield tests that also check intended behavior. Finally, evaluating CAT with additional open and closed LLMs, and repeating experiments to measure variance across runs, would clarify the extent to which its improvements depend on the model and on the randomness of LLM sampling.