Code evaluation · Research feature

Enhancing Automated Unit Test Generation for NLP Libraries Using Large Language Models

Automated unit test generation tools like EvoSuite perform well on general-purpose software but often struggle with domain-specific software such as Natural Language Processing (NLP) libraries, where inputs must follow semantic, syntactic, and structural constraints.

Adapted from research by Amirhossein Deljouyi, Annibale Panichella, Andy Zaidman.

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

Authors’ overview

Automated unit test generation tools like EvoSuite perform well on general-purpose software but often struggle with domain-specific software such as Natural Language Processing (NLP) libraries, where inputs must follow semantic, syntactic, and structural constraints. Large Language Models (LLMs) can generate domain-relevant test code, but tests produced by LLMs alone often fail to compile or achieve sufficient coverage. We propose LLMSuite, a hybrid test generation framework that integrates self-refinement prompting with class-level LLM reasoning into the search-based testing process. In this mechanism, the LLM iteratively improves its test snippets based on feedback from previous generations. This enables the model to produce increasingly precise, domain-consistent code fragments that steer the evolutionary search toward exercising complex and otherwise hard-to-reach behaviors. When no objective improves over multiple generations in the underlying evolutionary algorithm, these refined snippets are parsed and injected into EvoSuite’s population to expand the search space. To support our evaluation, we constructed a new dataset comprising 100 classes drawn from five widely used Java NLP projects. We also re-implemented CodaMOSA, a recent hybrid SBST-LLM technique, in Java to enable a direct comparison. Across this dataset, LLMSuite improves branch and line coverage by approximately 10% and 8%, respectively, and achieves an 11% higher mutation score than CodaMOSA-J. Compared to EvoSuite, LLMSuite yields roughly 15% higher branch and line coverage and 5% higher mutation score. Against an LLM-only baseline, it improves structural coverage by 36% and mutation score by about 24.7 percentage points. Finally, LLMSuite complements manually written test suites by exercising domain-specific behaviors that are often left untested.

Introduction

In today’s software-driven world, ensuring software reliability and correctness is critical. As a result, automated (unit) testing has become a fundamental practice for software engineers aiming to deliver high-quality software. However, writing tests is a tedious and time-consuming task. To reduce this burden, a variety of automated test generation techniques have been proposed. Notable tools in this area include Randoop and EvoSuite. EvoSuite, for instance, is a search-based software testing (SBST) tool that leverages evolutionary algorithms to create test suites, and has demonstrated strong performance in terms of code coverage, detecting software bugs, and helping developers during debugging.

Although these tools are effective for general-purpose software, their applicability to specialized domains like natural language processing (NLP) and machine learning (ML) libraries remains largely unexplored. This gap is especially concerning given the growing use of ML components in safety-critical systems, such as autonomous vehicles and legal document pipelines. NLP libraries are central to tasks like named entity recognition, sentiment analysis, and text classification, and are embedded in widely used frameworks such as Hugging Face Transformers. These libraries differ significantly from traditional software in structure, input expectations, and behavior. As a result, existing test generation tools often fail to produce effective test cases in these settings.

Large Language Models (LLMs) have shown strong generative capabilities across both code and natural language. However, their ability to generate high-coverage, compilable unit tests for complex systems remains limited. In contrast, SBST tools excel at systematically exploring execution paths, but lack semantic and contextual understanding. Together, these limitations reveal an opportunity for a complementary hybrid approach.

The goal of our study is to understand where and how LLM-generated snippets contribute most effectively in the context of NLP libraries, whose inputs must satisfy strict linguistic and structural invariants (e.g., grammatically well-formed sentences, valid parse trees, and coherent annotation pipelines).

We propose LLMSuite, a hybrid framework that integrates LLMs into the SBST pipeline. The key idea is to leverage the complementary strengths of both approaches: LLMs provide contextual insights and semantically meaningful inputs, while SBST ensures systematic exploration through evolutionary search. LLMSuite employs class-level prompting combined with a self-refinement strategy, in which the LLM iteratively improves its outputs based on feedback from previous generations. We hypothesize that this design enables the LLM to generate increasingly precise, domain-consistent test snippets that guide SBST toward exercising complex and otherwise hard-to-reach behaviors.

Experiment Setup

Baselines Selection. RQ1 and RQ3. We consider three baselines for comparison in RQ1 and RQ3: (1) EvoSuite, configured with the DynaMosa search strategy, (2) LLMOnly, which consists of test cases generated solely by ChatGPT-4o-latest-2025-07-12,, and (3) CodaMosa-J, using our Java re-implementation of the approach. Since the original CodaMosa was designed for Python, we reimplemented the high-level algorithmic logic as closely as possible– including the walkthrough procedure, the focus on low-coverage test targets, method level prompting, and the use of MOSA as the underlying SBST strategy. However, several components necessarily differ from the original implementation: CodaMosa’s study used OpenAI Codex, while we use ChatGPT-4o-latest, and we rely on our own Java parser in place of the Python-specific tooling used originally. LLMOnly test cases are similar to those used in LLMSuite but are not processed by our parser. As a result, this baseline may achieve higher raw coverage, due to the parser’s limitations in supporting certain code constructs.

RQ2. For RQ2, we conduct a systematic analysis of how individual components of our approach affect test coverage. Specifically, we examine: (1) the choice of LLM model, as well as the level of contextual information provided (method vs. class), (2) the prompting strategy, including the use of self-refinement, (3) techniques for refining string inputs, (4) the frequency of invoking LLM-based test generation. To isolate the effect of each factor, we design four experimental variants, each modifying a single component while holding others fixed. We evaluate test coverage of each variant in relation to both EvoSuite and the default LLMSuite configuration.

RQ4. In RQ4, we compare the test coverage achieved by LLMSuite with that of manually written test cases. This comparison is limited to the subset of classes in the dataset for which manually written tests are available.

Metrics for Evaluating Effectiveness. To assess the quality of a unit test suite for a given project, we use code coverage and mutation score. For coverage, we use metrics inspired by EvoSuite, which include instruction and branch coverage. Instruction coverage corresponds to Java bytecode instructions and is roughly equivalent to statement coverage at the source code level. Branch coverage measures whether both outcomes (true and false) of each conditional statement have been executed, effectively covering the edges in the program’s control flow graph. For mutation score, we utilize JUGE, a benchmarking infrastructure for evaluating Java unit test generators and it has been widely used in the yearly SBFT tool competitions. JUGE internally uses PITest to compute mutation scores, which quantify the ability of a test suite to detect injected faults (mutants). We extended JUGE to support Java versions 11 and 17 to ensure compatibility with our benchmark.

Manual Analysis. For RQ3 and RQ4, we conducted a manual analysis of test coverage. For RQ3, we examined classes with notable coverage differences between EvoSuite and LLMSuite, spanning various NLP functionalities. By identifying which parts of each class were covered by one approach but missed by the other, we gained insights into their relative strengths and limitations across different NLP tasks. For RQ4, we analyzed 27 classes that had both manually written test cases and were part of our dataset. For these classes, we first calculated branch coverage and mutation score for manually written tests, LLMSuite, and their combination. We then identified code blocks left uncovered by both the manual tests and LLMSuite, and investigated the underlying reasons for these gaps. Since the dataset was not very large, involving multiple coders was unnecessary. Instead, we followed Hoda’s guidance for single-analyst studies. The primary analyst conducted the coding, and the emerging codes and interpretations were regularly reviewed with the other researchers to ensure consistency and refine the analysis where needed.

RQ3: Improvement over SBST Approach

The mean branch coverage improvements achieved by LLMSuite across functionality categories are: Information Extraction (18%), Coreference (8%), Segmentation (7%), Normalization (5%), and Linguistic Labeling (3%). The gains are especially prominent in classes that are text-heavy and involve language-specific processing, as opposed to those focused on numeric computation, data structures, or utility logic. To better understand this, we analyzed classes where the differences were most pronounced.

A. Test Data and sequence of object calls. In many test cases, LLMs provide useful guidance for constructing objects and invoking them in the correct order. This is particularly important in classes that require complex setup, where uninformed search may get stuck in local optima due to the size of the search space. For example, for three classes in the CoreNLP project, in QuoteAnnotator (64% improvement), EntityMentionsAnnotator (41%), and WordsToSentencesAnnotator (39%), the improvements mainly come from LLMs generating correct sequences of instantiations and method calls.

Listing 8 in item B shows a representative example for EntityMentionsAnnotator. The test constructs a CoreLabel token, assigns entity type probabilities (e.g., PERSON at 0.95), wraps it in an ArrayCoreMap, and invokes the target method. EvoSuite struggles with such setup due to the specificity and inter-dependencies among objects. Such guidance also enables the exploration of behavior-dependent branches, such as error handling for invalid probabilities, as illustrated in item A of Listing 8.

C. Inferring Configuration and Property Settings. Some classes rely on external properties or configuration to activate certain branches. For example, in WordsToSentencesAnnotator, certain HTML boundary handling logic is only triggered when the appropriate configuration is set, which is shown in Listing 9.

Where LLM-Tests Provide Less Guidance. LLMSuite shows limited benefit in classes dominated by numeric computation or algorithmic logic, such as KMeans. In these scenarios, LLMs often fail to generate effective numeric inputs or encounter hallucinations, which we hypothesize can mislead the test generation process or trap it in local optima. As a result, the added value of LLM guidance is minimal, and in some cases, test quality may degrade slightly.

Taxonomy of Detected Gaps

To investigate how LLMSuite complements existing test coverage, we manually analyzed each project and its corresponding test cases to determine which parts of the production code were exercised by manually written tests and which areas remained untested. To better understand these uncovered regions, we manually reviewed the uncovered code blocks across the dataset and categorized the reasons for their lack of coverage. For this purpose, we adopted the classification scheme of Wang et al., originally proposed for analyzing test gaps in machine learning libraries. We adapted their scheme by adding two new categories—Method Overloading (MEO) and Properties-Dependent Behavior (PRB), marked with an asterisk (*)—and removing the message-handling behavior (MEB) category, which was not common in our dataset. This analysis showed that, in many cases, LLMSuite was able to extend coverage to code blocks that were not reached by the manual test suites. In the following, we illustrate both the covered and uncovered behaviors using examples from the CoreNLP project.

Valid Behaviors (VB). A class often supports multiple valid behaviors, but only a subset is exercised by manual tests. For instance, in CleanXMLAnnotator, the tests check whether an XML document starts and ends with a specific tag and whether tags include attributes. However, they cover only a few specific tags, leaving many supported ones untested. This partial coverage explains why some lines remain uncovered. Across all classes, 530 code blocks were left uncovered for this reason, accounting for 49% of all uncovered blocks. With LLMSuite, only 222 such blocks remained, primarily due to challenges in initializing complex objects.

Invalid Behaviors (IVB). In addition to valid behaviors, a class may also exhibit invalid behaviors when given inputs outside its expected domain, e.g., supplying a parameter with values beyond its allowable range. While manually written tests cover some cases (e.g., unclosed XML tags in Listing 11), they often miss others, such as having more closing than opening tags. This leads to 56 coverage drops across the manually written suite. In contrast, LLMSuite reduces this to just 16 cases by better addressing such edge scenarios.

Exception Handling (EX). Manually written tests often do not cover exceptions. For instance, in CleanXMLAnnotator, an exception is thrown when the appropriate tag annotation is missing, yet this is untested. We have discovered 56 such exception cases in the manual suite, whereas LLMSuite reduces this number by 11.

Auxiliary Methods (AUX). Our analysis reveals that many utility or helper methods remain untested in manually written tests, primarily because they are declared as private and are not directly invoked in typical test scenarios. This leaves 266 blocks uncovered, approximately 25% of all uncovered code. While LLMSuite and search-based techniques can sometimes reach these methods indirectly, testing private code remains challenging because bytecode instrumentation does not provide information about them.

Discussion

Test-generation time budget. We allocated a 15-minute time budget per target class. Within that time budget, LLM-based test generation with self-refinement on average consumes 148.2 seconds (16.1 seconds in zero-shot mode). This can reduce the time available for the search process when time is limited. However, since LLM test generation is independent of the search, this overhead can be avoided by running it in parallel with the SBST process.

Before parsing, the generated code goes through a hallucination-filtering stage. In the LLM component, we first try to repair generated snippets using the heuristics described earlier. Because using an LLM-in-the-loop repair mechanism would be too computationally expensive, we rely only on heuristic-based fixes and try to preserve as much of the generated code as possible. Across 474,626 LLM-generated statements, we found 39,980 hallucinated statements, including API mismatches. Rather than discarding the full test case, we comment out the hallucinated lines together with any dependent lines that become invalid as a result, while preserving the remaining valid statements so they can still contribute to testing. This leaves 434,646 hallucination-free statements and compilable, meaning that 91.57% of the generated lines remain usable. These cleaned tests are treated as LLMOnly test cases, for which we measure coverage independently, and are then passed to LLM2EvoSuiteParser for conversion into EvoSuite-compatible format.

Out of the 434,646 hallucination-free statements, 388,761 were successfully converted, corresponding to a conversion success rate of 89.44%. Among the remaining statements, 2,461 could not be parsed because they contain constructs that EvoSuite does not support, including for loops (691), foreach loops (605), while loops (515), if statements (344), and 306 other unsupported constructs such as new implementations of classes or interfaces. In addition, 43,424 statements could not be resolved during parsing. Most of these (40,393) involve API calls that EvoSuite does not support in the test generation process, such as when, spy, and fail. The remaining 3,031 statements include unsupported binary or unary expressions, such as mathematical operations or string manipulations like append.

Practical Value and Scope of LLMSuite. Although LLMSuite improves structural coverage, these gains should be interpreted carefully. Search-based unit testing techniques such as EvoSuite are intended for structural exploration rather than specification-based validation. In particular, regression-based oracles capture observed behavior, not necessarily intended functionality, and therefore do not guarantee semantic correctness. The generated tests should thus be viewed as complementary to manually written or specification-based tests.

Coverage is also only a proxy for test effectiveness. While higher coverage increases the chance of exercising diverse behaviors, it does not necessarily imply stronger fault detection. For this reason, we complement coverage with mutation score, which provides complementary evidence of fault-detection capability.

Conclusion

Automated unit test generation remains particularly challenging for domain-specific software, such as NLP libraries, where test inputs must satisfy semantic (e.g., domain-specific knowledge), syntactic, and structural (e.g., input data format) constraints. In this paper, we proposed LLMSuite, a hybrid framework that integrates Large Language Models (in particular ChatGPT-4o-latest-2025-07-12) into the search-based test generation approach within EvoSuite. When no search objective improves over multiple generations (search stagnation), LLMSuite invokes LLMs to generate class-level test suites with a self-refinement prompt strategy based on semantics (e.g., expressed in the JavaDoc and comments) and the structure of the class under test. These LLM-generated tests are injected into EvoSuite’s evolving population.

Across our evaluation of 100 classes from five widely used Java NLP libraries, LLMSuite improves branch and line coverage by 15% and mutation score by 5% over EvoSuite, outperforms an LLM-only baseline by 36% in structural coverage and approximately 24.7 percentage points in mutation score, and achieves 10% and 8% higher branch and line coverage than our Java re-implementation of CodaMOSA, with an 11% gain in mutation score (RQ1). When investigating design alternatives (RQ2), we found that the default configuration of LLMSuite consistently outperforms variants using different LLMs, alternative prompting strategies, fewer prompts, or string-only improvements–demonstrating the importance of class-level prompting, self-refinement, and tight integration with SBST. Our qualitative analysis (RQ3) shows that LLMSuite is particularly effective when meaningful inputs, correct API invocation sequences, or domain-specific configuration settings are required, while offering limited advantages for classes dominated by numerical computation or algorithmic logic. Finally, in examining its interaction with manually written tests (RQ4), we found that LLMSuite complements manual test suites by exercising behaviors and configurations that those tests do not reach, and combining the two leads to additional coverage through several recurring forms of complementary behavior.

We identify several directions for future work. First, an important extension is to compare LLMSuite against agent-based LLM systems that use compiler or execution feedback for iterative self-repair. While such approaches are promising, our framework was designed to give us full control over the entire generation, parsing, repair, and search pipeline within EvoSuite. Nevertheless, a direct comparison with external agentic baselines would be valuable future work. Second, future work should evaluate LLMSuite with other open-weight and closed-source LLMs. In particular, we plan to investigate the impact of other general-purpose models with different capabilities and alignment strategies. Because the framework is model-agnostic, these models can be incorporated without changing the overall architecture, enabling a broader assessment of generality across the evolving LLM landscape. We also plan to experiment with code-specific LLMs, e.g., StarCoder and DeepSeek Coder. In addition, it would be interesting to study whether integrating LLM-generated assertions more directly into the pipeline can improve behavioral validation beyond EvoSuite’s regression assertions. Finally, we plan to investigate LLMSuite in other domains where structured inputs and domain-specific semantics pose challenges for test generation, such as scientific computing libraries, parsers, and compilers.