logo SBA

ETD

Archivio digitale delle tesi discusse presso l’Università di Pisa

Tesi etd-06252026-194541


Tipo di tesi
Tesi di laurea magistrale
URN
etd-06252026-194541
Titolo
Adaptive Java Unit Test Generation with LLMs and Multi-Armed Bandits
Dipartimento
INFORMATICA
Corso di studi
INFORMATICA
Relatori
.
relatore Prof.ssa Semini, Laura
relatore Prof. Cossu, Andrea
Parole chiave
  • Adaptive input generation
  • Defect detection
  • Generazione automatica di test
  • Java
  • Large Language Models
  • Multi-Armed Bandit
  • Mutation testing
  • Software testing
  • Test generation with LLMs
  • UCB1
Data inizio appello
17/07/2026
Consultabilità
Completa
Riassunto (Inglese)
This thesis addresses the problem of automatically generating unit tests for Java classes using Large Language Models, with the goal of obtaining JUnit 5 suites capable of exercising relevant behaviors, verifying requirements, and detecting real defects. The work begins with the observation that a language model can produce syntactically plausible but semantically weak tests: assertions may confirm incorrect implementation behavior, cases may be redundant, or failures may not correspond to real bugs. For this reason, the thesis clearly distinguishes input search from assertion synthesis and evaluates the results with an independent oracle.

The developed framework receives a class under test, the related requirements in natural language, and, for final evaluation only, a corrected version of the class and an inventory of known defects. The pipeline is divided into multiple phases. First, a mutation space is constructed with PIT; then, an input search phase generates call sequences using specialized prompts for boundary values, state transitions, exceptions, and surviving mutants. These strategies are modeled as the arms of a Multi-Armed Bandit and selected with a variant of UCB1, which balances exploration and exploitation based on rewards derived from coverage and mutation scores. The selected inputs are then transformed into JUnit tests using a second model, constraining assertions to requirements rather than outputs observed on the faulty version. Finally, the tests are run on the oracle to distinguish confirmed defects, false positives, and regressions.

The experimental evaluation uses a controlled benchmark of eleven single-file Java classes, sorted by complexity and equipped with requirements, faulty implementation, correct implementation, and bug inventory. The proposed method, based on UCB1, is compared with two baselines: B1, a single-shot generation with an overall prompt, and B2, an iterative loop that randomly selects input strategies. The key metrics measure the number of distinct defects confirmed by the oracle and recall on the inventory; Coverage, mutation score, precision, false positives, regressions, and token cost are used to interpret the suite's overall quality.

The results show that iteration with feedback primarily improves the structural quality of suites compared to a single call, while the advantage in defect detection is more limited. UCB1 achieves the best averages for recall, mutation score, and coverage, with more evident benefits on complex classes, where the input space makes it more useful to adaptively choose the next strategy. On simple classes, however, a single well-constructed call is often sufficient. Cost is the main limitation: iterative strategies consume approximately three times more tokens than the single-shot baseline, and B1 remains the most efficient solution for confirmed defects. The thesis therefore concludes that adaptive selection is promising when the class presents difficult-to-explore state, interactions, and behaviors, but must be applied selectively and requires further testing on broader and more realistic benchmarks. The main contribution is methodological: separating generation, semantic validation, and cost analysis allows us to evaluate the tests produced by LLMs beyond their structural metrics alone.
Riassunto (Italiano)
La tesi affronta il problema della generazione automatica di test unitari per classi Java tramite Large Language Models, con l’obiettivo di ottenere suite JUnit 5 capaci di esercitare comportamenti rilevanti, verificare i requisiti e rilevare difetti reali. Il lavoro parte dall’osservazione che un modello linguistico può produrre test sintatticamente plausibili ma semanticamente deboli: le asserzioni possono confermare il comportamento errato dell’implementazione, i casi possono essere ridondanti, oppure i fallimenti possono non corrispondere a veri bug. Per questo motivo la tesi distingue chiaramente la ricerca degli input dalla sintesi delle asserzioni e valuta i risultati con un oracolo indipendente.

Il framework sviluppato riceve una classe sotto test, i relativi requisiti in linguaggio naturale e, solo per la valutazione finale, una versione corretta della classe e un inventario dei difetti noti. La pipeline è articolata in più fasi. Prima viene costruito uno spazio di mutazione con PIT; poi una fase di input search genera sequenze di chiamate usando prompt specializzati per valori limite, transizioni di stato, eccezioni e mutanti sopravvissuti. Queste strategie sono modellate come bracci di un Multi-Armed Bandit e selezionate con una variante di UCB1, che bilancia esplorazione e sfruttamento sulla base di ricompense derivate da coverage e mutation score. Gli input selezionati vengono poi trasformati in test JUnit tramite un secondo modello, vincolando le asserzioni ai requisiti e non agli output osservati sulla versione difettosa. Infine, i test vengono eseguiti sull’oracolo per distinguere difetti confermati, falsi positivi e regressioni.

La valutazione sperimentale usa un benchmark controllato di undici classi Java single-file, suddivise per complessità e dotate di requisiti, implementazione difettosa, implementazione corretta e inventario dei bug. Il metodo proposto, basato su UCB1, viene confrontato con due baseline: B1, una generazione single-shot con un prompt complessivo, e B2, un ciclo iterativo che seleziona casualmente le strategie di input. Le metriche principali misurano il numero di difetti distinti confermati dall’oracolo e la recall sull’inventario; coverage, mutation score, precisione, falsi positivi, regressioni e costo in token servono a interpretare la qualità complessiva della suite.

I risultati mostrano che l’iterazione con feedback migliora soprattutto la qualità strutturale delle suite rispetto alla singola chiamata, mentre il vantaggio sulla rilevazione dei difetti è più contenuto. UCB1 ottiene le medie migliori su recall, mutation score e coverage, con benefici più evidenti sulle classi complesse, dove lo spazio degli input rende più utile scegliere adattivamente la strategia successiva. Sulle classi semplici, invece, una singola richiesta ben costruita è spesso sufficiente. Il costo è il principale limite: le strategie iterative consumano circa tre volte più token della baseline single-shot, e B1 resta la soluzione più efficiente per difetto confermato. La tesi conclude quindi che la selezione adattiva è promettente quando la classe presenta stato, interazioni e comportamenti difficili da esplorare, ma va applicata selettivamente e richiede ulteriori verifiche su benchmark più ampi e realistici. Il contributo principale è metodologico: separare generazione, validazione semantica e analisi del costo permette di valutare i test prodotti dagli LLM oltre le sole metriche strutturali.
File