Authors’ overview
Recently, the emergence of Large Language Models (LLMs) has spurred a surge of research into automated unit test generation, yielding impressive performance and reducing manual effort. However, existing LLM-based approaches still suffer from two major limitations: (1) they follow rigid, procedural workflows that underutilize the autonomous reasoning potential of LLMs, making it difficult to dynamically adapt testing strategies based on real-time feedback; and (2) they rely on rule-based context extraction that is not tailored to test generation, failing to capture fine-grained code dependencies and test-specific knowledge required for deriving test requirements. In this paper, we propose TestAgent, an LLM-based test generation approach that addresses the above limitations by emulating human testing practices via a multi-agent collaboration mechanism. Particularly, TestAgent designs three specialized agents, namely a requirement planner, a test generator, and a test reviewer, to simulate how developers understand, construct, and validate unit tests. To unleash the autonomous capabilities of LLMs, we equip TestAgent with a set of tool APIs that can be invoked dynamically in an on-demand and adaptive manner. To further support repository-level reasoning, TestAgent constructs a test-specialized knowledge graph via static analysis, which captures code entities and their dependencies across the project and persistently stores testing artifacts (e.g., test reports and failure analyses) produced during generation. Experimental results show that TestAgent achieves 97.46% execution rate, 92.34% line coverage, 90.24% branch coverage, and 83.69% mutation score on six Java projects, outperforming LLM-based baselines across all metrics and achieving substantially higher mutation scores than search-based tools.
Introduction
Software testing is a cornerstone of modern software quality assurance. Among the various stages of testing (e.g., integration and system testing), unit testing plays a particularly critical role by verifying the correctness of individual software components early in the development lifecycle. As the cost of fixing software bugs increases significantly over time, early detection through unit testing substantially reduces maintenance overhead and improves development efficiency. Thus, unit testing has become a standardized and often mandatory practice as software systems continue to evolve and support a wide range of critical industries.
However, it is fundamentally challenging and labor-intensive for developers to construct high-quality unit tests manually. To mitigate manual efforts in writing unit tests, a variety of techniques have been proposed to automate test generation, including heuristic-based, random-based, and symbolic execution. Despite being promising, test cases generated by these tools typically suffer from limited readability, maintainability, and meaningfulness, which hinders their practical adoption in real-world development. For example, prior work reveals that assertions generated by traditional tools (such as EvoSuite and Randoop ) are not as meaningful and helpful as human-written ones in the industrial scenario.
Recently, the rapid advancement of Large Language Models (LLMs) has marked a new milestone in software engineering, demonstrating impressive capabilities in various tasks, such as code generation, summarization, and program repair. This progress has inspired researchers to explore LLM-based unit test generation from two directions: (1) training LLMs, which pre-trains or fine-tunes LLMs by collecting high-quality test generation training datasets and selecting efficient training strategies. (2) prompting LLMs, which constructs effective prompts by extracting code context, retrieving similar test generation examples, and designing task instructions. Among them, prompt-based techniques, especially those that adopt a generation-and-validation loop, represent state-of-the-art (SOTA) by generating initial test cases and refining them with dynamic feedback. Despite promising, these techniques still suffer from two major limitations.
❶ Challenge: Procedural Framework. Existing approaches typically follow a pre-defined and static generation pipeline that does not adapt the test generation strategy based on real-time feedback (e.g., whether to refine generated test cases or re-extract more relevant context). As a result, the generation process remains fixed regardless of intermediate outcomes, limiting its ability to explore alternative generation paths and hampering the effectiveness of LLMs in handling complex or evolving testing requirements.
❷ Challenge: Coarse-grained Context Extraction. Most existing approaches retrieve context using fixed rules (e.g., the entire focal method or the focal class), without explicitly modeling language-specific structures such as object-oriented hierarchies, method dispatch, and inter-class dependencies. For example, extracting only a focal method may omit essential external invocation information, whereas including the entire class or package may introduce irrelevant details and even exceed the input-length limits of LLMs. Although recent SE agents (e.g., RepoGraph and AutoCodeRover ) have explored repository-level code representations to support context retrieval, these representations are designed for general SE tasks such as issue resolution: they neither model test-specific entities and relations (e.g., test classes, test methods, and test–focal links) nor accumulate testing artifacts (e.g., test reports and failure analyses) produced during generation. Consequently, they provide limited support for deriving test requirements and reasoning about the intended behavior of the focal method.
LLM-based Agents
The rapid development of LLMs has opened new possibilities for building intelligent agents with broad adaptability. Agents, defined as artificial entities capable of perceiving their environment, making decisions, and taking actions, have been considered a promising pathway toward achieving Artificial General Intelligence (AGI).
The impressive performance of LLM-based agents has motivated extensive research in code-related domains. In the code repair domain, Jimenez et al. develop SWE-Bench, an evaluation framework comprising 2,294 real-world software engineering issues collected from GitHub. It has since become a benchmark for a growing body of agent-based approaches. For example, Yang et al. propose SWE-Agent, which employs a customized Agent-Computer Interface to empower agents to create and edit code files, navigate entire repositories, and execute tests. In the code generation domain, numerous agent-based studies have also been conducted.
Although sharing the high-level idea of agent-based repository understanding, TestAgent differs from prior SE agents in three aspects. First, existing repository representations, such as RepoGraph, are designed for general SE tasks (e.g., issue resolution) and capture only static code structures; in contrast, our knowledge graph is specialized for unit testing, which introduces test-specific nodes and relations (e.g., test classes, test methods, and test–focal links) and further serves as a persistent store for dynamically generated testing artifacts (e.g., function summaries, test reports, and root-cause analyses). Second, unlike AutoCodeRover, which navigates repositories via file paths and rule-based matching, our agent–computer interfaces resolve code entities and traverse inter-procedural relations (e.g., call graphs and inheritance) directly over the knowledge graph, and support dependency-based similar-test retrieval for test reuse. Third, to the best of our knowledge, TestAgent is the first work to incorporate requirement planning, test generation, and test reviewing into a multi-agent unit testing pipeline that emulates the human testing workflow.
Test Generator Agent
❶Context Retrieval. The agent begins by utilizing an external retrieval toolkit to actively query context information (e.g., program entities and dependencies) related to the focal method from the knowledge graph. The agent then assesses whether the current context is sufficient to support meaningful test generation. If so, it transitions to the next state; otherwise, it remains in the retrieval state to gather additional context information. To bound this loop, TestAgent adopts an elastic control strategy: the agent is explicitly queried about context sufficiency after 30 interaction turns, and test generation is enforced after 40 turns, within the maximum recursion depth described in Section IV-A.
❷Test Generation. Upon confirming adequate context, the agent synthesizes candidate test cases using a chain-of-thought-based reasoning prompt. This prompt guides the agent through step-by-step reasoning to construct structurally sound and semantically meaningful test cases that fulfill the given test requirements.
❸Execution Validation. The correctness of generated test cases is verified via an automated pipeline, in which the agent invokes external tools for syntax checking, compilation, and sandboxed execution. Test cases that pass all checks are directly added to the final suite; those that fail trigger the agent to enter the root cause analysis stage.
❹Root Cause Analysis. For any failing test case, the agent performs root cause analysis to determine the underlying reason: (1) Test Case Issue. If the failure is caused by minor flaws in the test case, such as incorrect arguments, weak assertions, or improper handling of edge conditions, the agent considers it recoverable. In this case, the test case is refined and re-entered into the generation-validation loop with detailed validation feedback. (2) Focal Method Issue. If the failure is likely caused by a defect in the function under test, the agent activates a defect confirmation mechanism. The mechanism invokes three LLMs with different training pipelines, each of which independently examines the test case, error message, and reasoning trace. If all three agree that the failure reveals a real defect, the test case is labeled as defect-revealing and added to the final test suite.
❺Generation Termination. Once a test case either successfully passes all validations or is confirmed to expose a real defect, the agent generates a structured report to record the testing outcomes, including line coverage, branch coverage, and mutation scores. These results are formatted into a JSON format report, which serves as feedback for the reviewer agent or as documentation for developer inspection when deployment. If the retry budget is exhausted before a compilable test is produced for a highly complex focal method, the agent records the last attempt as a best-effort result rather than discarding the method.
Test Reviewer Agent
The test reviewer agent is responsible for assessing the quality of generated test cases from multiple perspectives, and providing actionable suggestions that are iteratively fed back to the above two agents to guide their subsequent behaviors of both test cases and test requirements. To automate this process, this agent operates in two internal states: quality evaluation and suggestion derivation.
In the quality evaluation state, the agent receives the full context required for assessment, including the function definition, function summary, related test requirements, generated test cases, and execution reports. It then analyzes each test case based on multiple criteria, including syntax validity, compilation success, runtime behavior, structural coverage (e.g., line and branch coverage), alignment with test requirements, and defect detection capabilities (e.g., mutation score), to generate an evaluation summary.
In the feedback analysis state, the agent translates evaluation results into actionable decisions for both test cases and test requirements. For each test case, it assigns one of four feedback actions: (1) Accept. The test case satisfies the expected requirement, achieves meaningful coverage, and exhibits strong fault detection (e.g., kills mutants or reveals defects). Thus, it is retained for deployment without modification. (2) Discard. The test case fails to meet the intended requirement and contains unrecoverable flaws. Thus, it is removed from the generated test suite, and its related graph entries are deleted (i.e., calling delete_test_cases tool in Table I). (3) Update. The test case is partially valuable but incomplete, e.g., minor syntax or compilation errors, partial coverage, or weak assertions. Thus, it is retained with concrete suggestions for improvement. (4) Augment. If a test case exhibits inadequate coverage or fault detection due to insufficient test requirements, the agent infers new test requirements targeting untested scenarios, such as uncovered paths, unhandled exceptions, or surviving mutants.
Dataset
We evaluate TestAgent using three distinct datasets to comprehensively assess its performance from multiple perspectives. First, in RQ1-RQ3, consistent with prior studies, we collect six Java projects from GitHub, resulting in a dataset containing 1,454 focal methods. Five of these projects originate from Defects4J, a widely recognized benchmark dataset frequently utilized in previous evaluations, and we adopt the same five projects used in prior LLM-based test generation studies to ensure a consistent comparison with baselines. Due to resource constraints, we randomly select 200 methods each from the Lang and Chart projects, both of which originally contain thousands of methods. To evaluate the performance of TestAgent in complex methods, we also include another project, Ruler, identified by HITS as particularly challenging. Second, in RQ4, we introduce an internal dataset named UTXXX, to assess how TestAgent performs on previously unseen industrial methods. This dataset, sourced from industry, comprises 658 focal methods collected from four Java projects. Finally, in RQ6, to evaluate the applicability of TestAgent to Python programs, we follow the approach of CodaMosa and select nine modules from three Python projects. These modules form a Python dataset, referred to as CM, containing a total of 141 focal methods. Since the open-source subjects are mainly library projects, the industrial dataset in RQ4 further complements them with projects that better reflect industrial practice. The details and statistics of these datasets are summarized in Table II.
RQ3: Model Adaptability of TestAgent
Design. RQ3 investigates the generalizability of TestAgent across different base LLMs. We select three representative LLMs: GPT-4o, DeepSeek-V3, and Qwen3-30B-A3B. These models include both closed-source and open-source LLMs with varying model sizes, accessed via API or deployed on independent hardware. This setup demonstrates the model-agnostic characteristic of TestAgent and its adaptability to diverse deployment scenarios.
Results and Analysis. Table V summarizes the performance comparison among the selected LLMs. GPT-4o consistently achieves the best overall performance, followed by DeepSeek-V3, with Qwen3-30B-A3B showing the lowest performance. This ranking aligns with their corresponding deployment costs and capabilities. Regarding test correctness, all three models achieve a syntax correctness rate of 100%, indicating robust language modeling abilities. Regarding compilation and execution success rates, GPT-4o and DeepSeek-V3 both exceed 97%, whereas Qwen3-30B-A3B shows a noticeable performance degradation, with compilation success dropping to 94.57% and execution success declining further to 85.63%. Regarding test adequacy, GPT-4o leads substantially, achieving 92.34% line coverage, 90.24% branch coverage, and 83.69% mutation score, reflecting superior capability in generating high-quality test cases. DeepSeek-V3 trails GPT-4o by approximately 6% in both line and branch coverage, and by roughly 11% in mutation score. Qwen3-30B-A3B exhibits the lowest adequacy, with 81.25% line coverage, 78.21% branch coverage, and 60.44% mutation score. However, it still substantially surpasses ChatUniTest (even when using GPT-4o), highlighting the effectiveness of TestAgent regardless of the underlying LLM.
We also observe that TestAgent with Qwen3-30B-A3B trails EvoSuite on line and branch coverage (by 0.86% and 2.60%, respectively), which stems mainly from the limited context understanding and requirement analysis capability of this smaller open-source model. Nevertheless, it remains well ahead of EvoSuite on mutation score (60.44% vs. 43.59%), while incurring zero API cost due to local deployment. In this light, we regard TestAgent and EvoSuite as complementary rather than strictly competing approaches: EvoSuite excels at maximizing structural coverage at very low cost, whereas TestAgent contributes higher mutation scores and more readable, requirement-aligned tests (see RQ5). Combining the two, e.g., seeding TestAgent with EvoSuite-generated tests to close residual coverage gaps, is a promising direction for future work.
RQ4: Industrial Project Performance
Design. To mitigate potential data leakage risk, RQ4 assesses the performance of TestAgent and baseline methods using UTXXX, a real-world industrial dataset comprising 658 target methods from four distinct projects. Due to the confidential policy of the company, we hide the information about internal subjects. The UTXXX adopts a unified Maven architecture with the JUnit 4 testing framework. The projects have never been publicly released, substantially reducing the risk of exposure during LLM pre-training. This setup aligns with mainstream development practices and provides a more accurate measure of capability for generating test cases in contemporary Java projects. Specifically, we use the Qwen3-30B-A3B hosted on the local server. However, due to limitations in this model’s capability, it could not perform code slicing—a crucial step required by the HITS approach. Consequently, we excluded HITS from this comparison. To objectively measure the effectiveness of each testing approach, we used three widely adopted metrics: line coverage, branch coverage, and mutation score.
Results and Analysis. Table VI presents the performance results of each approach evaluated on the UTXXX dataset. As shown, TestAgent consistently achieves the highest performance across all three metrics. Specifically, TestAgent attains a line coverage of 84.21%, branch coverage of 82.12%, and mutation score of 55.38%, clearly outperforming the other methods. ChatUniTest exhibits comparable performance to EvoSuite in terms of line coverage and branch coverage, but achieves a noticeably higher mutation score. Overall, these results demonstrate that TestAgent substantially outperforms baseline approaches, highlighting its effectiveness in generating high-quality unit test cases for industrial Java projects.
Conclusion
This paper presents TestAgent, a novel multi-agent framework for LLM-based unit test generation, which emulates human testing practices with three collaborative agents: a requirement planner, a test generator, and a reviewer agent. We further equip the agents with external tool APIs and a repository-level knowledge graph, enabling agents to interact with the codebase in a fine-grained and adaptive manner. Extensive experiments on both Java and Python projects demonstrate that TestAgent outperforms state-of-the-art LLM-based approaches across various dimensions and achieves substantially higher mutation scores than search-based tools. Moreover, TestAgent exhibits strong extensibility across different LLM backbones and practical applicability in industrial scenarios.


