Code evaluation · Research feature

MR-Coupler: Automated Metamorphic Test Generation via Functional Coupling Analysis

The study evaluates MR-Coupler, a system that generates metamorphic test cases by analyzing functional coupling between methods in software source code.

Adapted from research by Congying Xu, Hengcheng Zhu, Songqiang Chen and colleagues.

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

Editor’s introduction

The study evaluates MR-Coupler, a system that generates metamorphic test cases by analyzing functional coupling between methods in software source code. It compares the effectiveness of MR-Coupler to existing approaches by measuring the rate of valid test case generation and false alarms. The research shows MR-Coupler produces valid test cases for over 90% of tasks and reduces false alarms by 36.56% compared to baseline methods. It detects 44% of real-world bugs, with improvements attributed to identifying functionally coupled method pairs and using real invocation examples to guide test input generation. The system leverages three coupling features to narrow the search space, identifying 6.93 relevant methods per target method from 30.44 candidates. Manual inspection confirms that specific bugs are exposed only through coupling between certain methods, such as randomRepo and repos, which share access to common fields. A key boundary is that input augmentation, while improving test coverage, is not essential for generating valid test cases, as 98 tasks still produce valid results without it, though false alarm rates increase slightly due to reduced input diversity.

Introduction

Metamorphic testing (MT) is a powerful testing technique that helps address the test oracle problem. Specifically, MT tackles this challenge by leveraging relations between multiple outputs (i.e., output relation) given the relations between corresponding inputs (i.e., input relation). In this case, the logical implication from input relation to output relation defines a metamorphic relation (MR). MT has been shown to be effective in various software systems, especially where the expected outputs are difficult to specify (e.g., large language models, compilers, machine translation, question answering systems, etc.). One MR can serve as an oracle applied to many test inputs to exercise diverse program behaviors and enhance test adequacy.

Despite its potential, the adoption of MT is challenging. A key bottleneck is the construction of effective MRs, which requires domain-specific knowledge. Although several attempts have been made to explore the generation of MRs, these approaches suffer from (i) reliance on manual effort, (ii) assumptions of regression testing scenarios, (iii) restriction to specific domains, or (iv) requirements for high-quality specifications. All these studies rely on knowledge that is hard to obtain. Although a recent study reported the possibility of mining the fragmented knowledge required by MRs from test cases, it also found such test cases to be rarely available: they account for only 1% of the studied test cases and are scattered in only 20% of the studied projects. The lack of automatic methodologies for constructing metamorphic test cases (MTCs) hinders the widespread adoption of MT. To ease its adoption, a technique without the above-mentioned limitations is expected. To construct such a technique, a central challenge is to formulate MRs without relying on knowledge that is hard to obtain.

However, leveraging functionally coupled methods to construct MRs requires addressing two technical issues. First, given a target method, there can be dozens of candidate method pairs, and it is expensive to enumerate all possible method pairs blindly for MR construction. Thus, there is a need for a precise mechanism to identify functionally coupled method pairs, which provides better focal methods for subsequent MR construction. Second, while LLMs enable MTC generation via code understanding and reasoning, the resulting MTCs can be invalid due to hallucination. Therefore, we need an effective mechanism to validate the generated MTCs, which allows us to avoid overwhelming developers with false alarms.

To tackle these technical issues and effectively generate MTCs, we propose MR-Coupler, an automatic MTC generator for a given target method. It operates in three phases. First, it identifies functionally coupled methods as ingredients for MR construction, based on their signature commonality, functional call, and state interaction. This design is informed by our observation of human-written MTCs and thereby addresses the first technical issue. Second, it employs LLMs to generate MTCs based on each identified functionally coupled method pair by providing relevant and minimal context. Specifically, we instruct LLMs to understand their functionalities and reason about potential MRs between them. To reduce hallucinations that lead to invalid MTCs, we provide an MTC template and retrieve API usages for LLMs to follow. Finally, it validates the generated candidate MTCs via test amplification and mutation analysis. To validate the MTCs without a given ground truth, we create mutants from the original program by injecting artificial faults, and expect more amplified MTCs (from the candidate MTC) to pass on the original version compared with the faulty mutants. This filtering strategy is based on a property of MT: the MR embedded in a correct MTC should apply to many other inputs to effectively kill mutants.

Phase 1: Coupled Methods Identification

This phase is to identify the functionally coupled methods of the target method for MR construction. However, given a target method and its container class, it is non-trivial to identify the functionally coupled methods that are suitable for MR construction.

On the one hand, classes often contain dozens of methods. For example, in our dataset, there are over 30 candidate methods in a class for each target method on average. Naively including all candidates not only increases the cost of LLM tokens but also risks of introducing noisy context, which distracts LLMs. The difficulty is to identify those methods with relevance (e.g., producer–consumer, equivalent or inverse functions) suitable for MR construction.

Human-Written MTCs

The first dataset contains 1,471 MTCs written by developers in open-source Java projects. Each entry in this dataset consists of a human-written MTC and a corresponding pair of MR-coupled methods. These MTCs are valid and executable. Such a dataset is leveraged to (i) evaluate the validity of automatically generated MTCs (RQ1), by running them on executable target methods, and (ii) measure the similarity between the human-written MTCs and MR-Coupler generated MTCs, by checking whether they encode the same MR-skeletons (RQ4).

To construct such a dataset, we adopted a strategy similar to Xu et al.. Specifically, we collected a list of high-quality Java projects (i.e., with at least 50 stars) from GitHub. The query was done on December-16, 2024, which returned over 24,000 projects. We then ran MR-Scout to discover human-written MTCs from these projects, which yielded 46,006 candidate MTCs. With these candidates, we applied three filtering criteria to select the valid and executable MTCs: (i) they must compile, as we need to compile and run the test cases in our experiments; (ii) they must pass in the latest version of the project to ensure the MTCs are valid; and (iii) the commit introducing these MTCs must mention an issue number in its commit message (e.g., containing “#123”). We prioritize such tests since they are often extensively discussed and reviewed to disclose the issues and thus tend to be of high quality.

Experiment Results

The improvements are from two key factors. On the one hand, providing LLMs with functionally coupled methods serves as a hint, effectively inspiring them to infer valid MRs and then generate valid MTCs, thereby reducing hallucinations. Without such context, coming up with MRs from scratch is challenging for LLMs, leading to higher rates of invalid MRs. On average, MR-Coupler identified 6.93 relevant methods per target method from 30.44 candidate methods in their container classes, significantly narrowing the enumeration space. On the other hand, retrieving real invocation examples helps LLMs construct valid input objects and correctly invoke methods, particularly when methods require complex object instantiations. This context helps generate 83.69% to 93.08% executable MTCs, which are 54.35% more compared with baselines.

Failure analysis. When built with DeepSeek-V3.1-Think, MR-Coupler fails to generate any valid MTCs for two target methods. This is because, for one target method, execution requires access to external or environmental resources (e.g., a JSON file or environment variable), but no invocation examples were available in the repository as the context. As a result, MR-Coupler failed to configure these resources in the generated MTCs, leading to non-executable tests and no valid MTCs. For the other target method, MR-Coupler generated all executable but invalid MTCs (i.e., false alarms).

MR-Coupler exhibits a 5.5% false-alarm rate when built with DeepSeek-V3.1-Think. There are two main reasons. (i) MR-Couplerrelies on Major to generate mutants for validation (Section 3.3.2). For some target methods, Major failed to execute due to environmental issues (e.g., uncompilable dependencies), preventing mutant generation and disabling the validation step that filters false alarms. (ii) For some cases, the generated MTCs cannot reveal the injected mutants, and do not expose behavioral differences between the base and mutated versions – the pass rates are identical, causing MR-Coupler to retain false alarms.

Correctness of Generated MTCs

While the above automatic and objective metrics evaluate the validity of generated MTCs by checking the necessary properties and their execution results, this does not guarantee the semantic correctness of the underlying MRs. A generated MTC may satisfy these validity criteria yet still be semantically incorrect or meaningless (e.g., vacuous oracles). To assess the semantic correctness, we further conduct a manual study to validate whether generated MTCs indeed reflect correct MRs for the target method.

Setup. For each of the 100 target methods in RQ1, we manually inspected one randomly selected MR-Coupler-generated MTC. Two participants (each with over four years of experience in Java and metamorphic testing) independently validated each selected MTC. For cases with disagreement, the two participants discussed and reached a consensus.

An MTC is deemed correct if it reflects an MR present in the code; it may miss failures but must not produce false alarms. For each MTC, participants first understand the functionality of the target method and its coupled method. They then analyzed the underlying MR an MTC and determined whether an MTC is correct. Particularly, they assess whether any valid input could violate the assertion and checked execution for false alarms. If any of the cases is found, the MTC is incorrect.

Result. Among the 100 sampled MTCs, 8 were Incorrect, and 3 are too domain-specific and complicated to understand and validate their correctness. The incorrect cases mainly involved faulty test implementations (e.g., triggering IllegalArgumentException or NullPointerException) or MRs not holding for corner-case inputs. The remaining 89 MTCs were Correct. The inter-rater agreement between participants was high (87%), and disagreements were resolved through discussion. Overall, these results suggest MR-Coupler’s effectiveness in generating correct MTCs.

Experiment Result

Based on manual inspection, we attribute the improvement to two main factors: (i) Coupling-aware MR construction.Some bugs are exposed only by MRs over specific method pairs, and MR-Coupler can generate such MRs through its effective coupled methods identification. For example, a bug in the method randomRepo is revealed when coupled with the method repos, as both invoke MkRepo and access shared fields (storage, self). This allows MR-Coupler to identify the coupling and then generate an effective MR. (ii) Input augmentation.Some bugs require specific input to trigger. By applying additional inputs (Section 3.3.1), MR-Coupler exercises diverse behaviors and exposes corner cases, such as boundary inputs in previousClearBit (e.g., i = 1<<16). In addition, among all evaluated LLMs, DeepSeek-V3.1-Think reveals the most bugs, likely due to its reasoning ability. By analyzing the code and understanding the coupling between methods, it can identify fault-prone interactions and construct effective MRs.

By analyzing the overlap of bugs revealed by MR-Coupler with different LLMs, we observed that a total of 28 bugs were revealed, with 8 detected by all models and both DeepSeek-V3.1-Think and Qwen3-coder-Flash uniquely revealed two additional bugs. This suggests that combining models could further improve the bug-revealing capability. This is an interesting strategy for future enhancement. Notably, 19 of the 22 bugs found by DeepSeek-V3.1-Think are exposed by multiple distinct MRs. For example, a bug in multiply can be revealed by different algebraic relations. This highlights that MR diversity plays a role in enhancing the bug-revealing capability.

Failure analysis. While MR-Coupler successfully detected 22 (44%) real bugs originally revealed by human-written MTCs, some bugs remained unrevealed. A major reason is that some buggy methods are highly domain-specific and implement complex business logic, where providing only the method code is insufficient for LLMs to infer the intended behavior (e.g., a bug related to “compaction file metrics” in Apache IoTDB ). Module-level or project-level knowledge is required. Automatically extracting and providing such knowledge as the context for LLMs remains a challenging and promising direction for future research. In other cases, constructing inputs required access to external resources, such as environment variables or specific file contents. When no concrete examples were retrieved in the project under test, MR-Coupler-generated MTCs failed to set up that, resulting in non-executable or non-bug-revealing tests. Effectively retrieving and adapting such project-level context for test generation is still an open challenge.

Threats to Validity

Representativeness of LLMs. Since MR-Coupler relies on LLMs for MTC and input generation, one potential threat is whether our findings based on the selected LLMs are representative. To mitigate this threat, according to the EvalPlus leaderboard, we include representative LLMs from three well-known LLM families, i.e., GPT-4o mini from OpenAI,Qwen3-coder-Flash from Alibaba, DeepSeek-V3.1 and DeepSeek-V3.1-Think from DeepSeek.

Another potential data leakage arises from providing underlying MTCs as examples during the MTC generation (Section 3.2). In the evaluation, we excluded all detected MTCs from the examples and manually inspected results for 50 buggy subjects (Section 4.1.2), finding no such leakage.

Representativeness of Experimental Subjects. A potential threat concerns the generalizability of our findings across projects and programming languages. To mitigate the first one, we selected representative Java projects (Section 4.1), following the strategy of prior studies. Due to the substantial effort required to collect reproducible MT-revealed bugs, this study focuses on a single widely used language (Java) and evaluates the bug-revealing capability of MR-Coupler (RQ2) on 50 Java bugs. This constitutes a limitation of our study — the generalizability of our findings to other programming languages is not evaluated. Constructing a benchmark of multiple programming languages is a meaningful direction for future work.

Quality of Ground Truths. We use human-written MTCs as ground truth and treat the fixed or latest program versions as bug-free when answering the RQs on validity, bug revealing, and similarity. A potential threat concerns the quality of these ground truths. To mitigate this, we applied three filtering criteria to select high-quality MTCs and corresponding target methods (Section 4.1). We further manually validated the developer-written MTCs for the 100 sampled entries in RQ1, following the criteria of MR-Scout. We found that 99 out of 100 MTCs are valid, with only one too complex to understand and validate. This aligns with the 0.97 precision reported by MR-Scout, indicating the high quality of these ground truths.

LLM-Based Automated Test Generation. Recent work has demonstrated the broad utility of LLMs in software testing, including unit test generation, fuzzing, and test-oracle construction. studied LLM-based unit test generation and reported substantial potential as well as challenges in reliability and coverage. A cited study further showed that LLM prompting can drive effective, language-agnostic fuzzing. A cited study investigated neural test-oracle generation and highlighted the need for robust validation. These advances motivate LLM-based MT, where oracle construction remains a central bottleneck.

LLM-Based MR Generation. Several recent studies have explored using LLMs to generate MRs and other MT artifacts. A cited study proposed an LLM-based technique to automatically deduce input transformations from pairs of source and follow-up inputs. derived MRs from requirement specifications and translated them into SMRL, a domain-specific MR language, via a two-phase LLM pipeline. A cited study proposed a human-AI hybrid MT framework that uses predefined MR patterns to generate MRs for autonomous driving systems. leveraged LLMs to discover input and output variables from scientific software documentation for constructing MRs. A cited study designed a multi-step prompt engineering pipeline to generate MRs for embedded graphics libraries, nearly doubling structural coverage and uncovering 14 new bugs compared to manually crafted MRs. These approaches show promise but either target specific domains, depend on auxiliary artifacts (e.g., requirement documents or API manuals), or require substantial human intervention.

Some studies evaluated LLM capabilities for MR generation. A cited study conducted a pilot study using ChatGPT (3.5) for MR generation in autonomous driving and found it effective at proposing useful MR candidates. examined ChatGPT (GPT-4) across nine systems of varying complexity and reported that, while correct MRs can be generated, the majority of candidates were either vaguely defined or incorrect, especially for complex or previously untested systems. A cited study evaluated MR discovery across 37 subjects and found that 4.6–38.6% of existing MRs were rediscovered but only 29.9–43.8% of generated MRs were valid. A cited study further showed that stronger models (e.g., GPT-4) improve MR quality over weaker ones, though human expertise remains essential for adjudication and refinement. In contrast, MR-Coupler leverages LLMs’ reasoning capability to derive MRs from functionally coupled methods and generate concrete executable MTCs, providing an end-to-end automated and self-validating pipeline.

Traditional MR Generation Approaches. Prior to LLMs, MR generation techniques relied on search-based, pattern-based, genetic-programming-based, or heuristic approaches. and generated MRs via genetic programming but assumed a regression testing scenario. and proposed search-based approaches to inferring MRs for numeric programs. and identified MRs based on predefined patterns, limiting generalizability across domains. A cited study proposed MemoRIA to identify equivalence MRs from documentation. Recently, derived MRs from existing test cases. However, these approaches rely on scarce resources (i.e., MR-embedded documents or tests). In contrast, MR-Coupler directly generates MTCs from the target program without relying on such resources, and is not restricted to the regression testing scenario.

Conclusion

This paper presents MR-Coupler, a fully automated approach to generate MTCs directly from the target program via functional coupling analysis. MR-Coupler first identifies functionally coupled method pairs based on signature commonality, function call, and state interaction. It then employs LLMs to generate concrete MTCs and refines them based on execution feedback. Finally, MR-Coupler amplifies and then validates the MTCs based on mutation analysis.

Our evaluation shows that MR-Coupler effectively generates valid MTCs for 98% of tasks and successfully reveals 22 confirmed bugs, improving valid MTC generation by 64.90%, and reducing false alarms by 36.56% compared to baselines. Moreover, MR-Coupler-generated MTCs achieve high consistency with human-written MR-skeletons, demonstrating MR-Coupler’s potential to assist or even partially replace developers in constructing effective MTCs across diverse domains.