Editor’s introduction
The study assesses six large language models and three coding agents across 165 real-world Java and Python testing scenarios, measuring their ability to generate executable mock objects, stubs, and assertions. It compares the outputs against validated reference artifacts, focusing on executability, behavior fidelity, and interaction-fault detection. Results show coding agents outperform LLMs in producing executable code, though this does not consistently translate to better behavior fidelity or fault detection. The findings indicate that while these tools advance mock generation, they still fall short of fully reliable, behaviorally faithful alternatives in real-world testing contexts.
Introduction
Unit testing is a cornerstone of modern software quality assurance. In practice, a software component (e.g., a Java class or method) commonly depends on other components, such as databases, payment gateways, file systems, or network services, thereby fulfilling its functionality. Testing such a component in isolation is challenging because its correctness depends on the correctness and availability of these dependencies. Mocking addresses this challenge by replacing real dependencies with simulated substitutes, known as test doubles, that mimic the behavior of actual dependencies for testing purposes only. Normally, A well-formed mock-based test involves three interdependent artifacts: (1) Mock objects answer the question of what to mock, i.e., which dependencies should be replaced to achieve proper test isolation. (2) Stubs answer the question of how the mock should behave. Specifically, they specify the return values, side effects, and exception scenarios that the mock should produce when its methods are called. (3) Mock assertions check whether the dependencies were used correctly, including their argument values, invocation counts, call order, etc. Listing 1 illustrates a JUnit test case with all three mocking artifacts implemented with Mockito framework.
The test exercises the focal method, charge, whose faulty and correct implementations are shown in Lines 15-21 and Lines 27–33, respectively, in a scenario where the payment can be authorized a charge up to three times, retrying only on a TimeoutException. To isolate the focal method from the actual dependency, the test creates a mock object for BankClient, namely bank (Line 4), and passes it to PaymentService as an initialization parameter (Line 10). The stub on Lines 5–7 specifies consecutive reactions on this mock object: the first call to authorize throws a TimeoutException, simulating a transient network fault; the second returns true, indicating a successful authorization, thereby testing the loop logic of the focal method with the follow-up mock assertions. As such, the focal method, charge, can be tested in isolation with mock objects and stubs. Continuing, the oracle assertion on Line 12 (assertTrue(ok)) validates the final output, while the mock assertion on Line 13 verifies that authorize was invoked exactly twice on the same mock object with the specified card id and amount. Obviously, the correct focal method immediately returns true at the second invocation of authorize, whereas the faulty one continues the loop and makes an unnecessary third call to authorize. Although they both pass the oracle assertion, the mock assertion reveals the fault of the latter.
As can be seen, systematic mocking, as in the example above, is effective for test isolation and fine-grained program verification. However, it is also noted that crafting all three kinds of artifacts by hand is labor-intensive and error-prone because they are tightly coupled to the specific implementations of the focal methods and their test cases, making them even more fragile to consistent code evolution. As such, mocking artifact automation has consequently been a long-standing research goal. Previous studies fall into three categories: (1) capture-and-replay approaches, (2) evolutionary algorithms, and (3) LLM-based testing tools. (1) Capture-and-replay approaches generate mock artifacts by first executing the actual dependency to record its runtime interactions, then replacing the dependency with a mock object and replaying the recorded behavior. While straightforward, these approaches have a fundamental constraint: they require the actual dependency to be runnable. Spadini et al. showed that 83% of mock-using test cases are introduced precisely when the actual dependencies are hard to set up, flaky, or unavailable, rendering capture-and-replay inapplicable in the majority of realistic mocking scenarios. (2) Evolutionary algorithms (e.g., StubCoder ) overcame the runnability requirement by optimizing the permutations and combinations among symbols to directly produce executable mocking artifacts. Nonetheless, their symbol pools are confined to literals within the focal method and associated test file, for the sake of improving symbol reusability and avoiding search space explosion. Consequently, it cannot synthesize return values or exception types that do not already appear in this narrow scope. (3) We have also noted that some LLM-based unit test generation studies passingly produce test stubs to ensure the tests can execute, yet the quality of these stubs was not evaluated. We agree that LLMs or even coding agents are promising workarounds for mock-based testing, as they reason over source code semantics rather than depending on runnable dependencies or local symbol pools. Moreover, coding agents can further leverage project-wide context, build systems, and execution feedback to iteratively refine their outputs. Nonetheless, their generative quality on the end-to-end pipeline of mock objects, stubs, and assertions is unexplored in the literature.
Related Work
Mocking is a core practice for isolating dependencies in unit tests. Spadini et al. conducted the first large-scale empirical study on when developers choose to mock. Ahmed et al. complemented this perspective by analyzing 25,302 mocking-related questions on StackOverflow, identifying that mock configuration and framework-specific API usage remain persistent developer pain points. More recently, Hora et al. analyzed over 1.2 million real-world commits on GitHub and found that coding agents add mocks more frequently than human developers, and this trend is growing. Qin further revealed a divergence in mock decisions between LLMs and developers. Going beyond empirical observation, Zhu et al. proposed MockSniffer, an ML-based approach to automatically recommend which dependencies to mock, but it only outputs binary decisions rather than generating actual mock code. With the rise of LLMs for test generation, a few works have touched upon mocking. MockMill extracts mocking information from existing developer tests to guide LLMs for new test generation. Notably, MocklessTester takes the opposite direction by deliberately avoiding mocks, which implicitly acknowledges that handling dependencies is a known pain point for LLM-driven test generation.
Beyond deciding what to mock and generating mock objects, an equally important challenge is generating stub behavior, including the return values, side effects, and exception handling that make mocked dependencies behave realistically in tests. Early automated stub generation efforts, from capture-and-replay that records actual dependency behavior, to EvoSuite’s built-in stubs that target environment-dependent classes with handcrafted rules, share a common limitation: they either require the actual dependency to be available and executable, or rely on domain-specific heuristics that cannot generalize to arbitrary dependencies. StubCoder overcame these constraints by using an evolutionary algorithm guided by runtime test behavior to synthesize stub code without needing the actual dependency, and in a domain-agnostic manner. Some automatic testing approaches also involve stub generation, such as AUTS, Bach et al., and IntUT, which aim to make generated tests executable; however, stub quality was not isolated as an evaluation target. Besides, Cheddadi et al. did not propose any approach; instead, they demonstrated the use of Google Test/Google Mock to write stubs for embedded verification.
Mock assertions check whether mocked methods were invoked with expected behaviors, which are the third essential component of mock-based testing. Zhu et al. conducted the first empirical study on mock assertions, characterizing their adoption, patterns, and usage in open-source projects. Their findings provide valuable insights into how developers write mock assertions, but the study is purely descriptive without addressing automated generation. Tiwari et al. proposed RICK, which monitors production execution data to generate mock-based artifacts (mock objects, stubs, and assertions) derived from production interactions to detect regression faults. However, it fundamentally depends on production deployment to collect execution traces and the Spoon metaprogramming framework for rule-based code generation, making it inapplicable during the development phase that is the focus of this study.
Task Definition
As illustrated in Listing 1, the unit tests considered in MockBench are organized according to the Arrange–Act–Assert (AAA) pattern. The Arrange phase creates and configures mock objects, including their stub calls; the Act phase invokes the focal method, i.e., Method Under Test (MUT); and the Assert phase checks the test outcome through oracle assertions and, when applicable, mock assertions that verify expected interactions with mocks.
Benchmark Design
Java Portion For the Java portion, we build upon StubCoder, which provides 59 real-world test cases across 13 projects with genuine mock configurations, production code, and compilation dependencies. However, not all external dependencies are mocked, and the existing mock assertions do not always fully specify the expected dependency interactions. Therefore, further refinement is needed for our evaluation.
Specifically, following a pervasive mocking practice, we first select MUT-dependent objects that come from third-party libraries or outside the class of the MUT for mocking. Next, for each selected dependency in the MUT, we progressively add mock objects, stubs, and mock assertions if they are missing in the original test. Our modification does not change the production code, focal calls, test inputs, or fixtures. We also augmented the suites with oracle assertions to verify the observable outcomes of stubbed behaviors. In total, 53 of the 59 Java test suites received additional checks: oracle assertions increased from 117 to 201, while mock assertions rose from 61 to 126. Consequently, all 59 suites now enforce explicit interaction verifications, up from only 30 in the original baseline. We implement tests using JUnit alongside Mockito, managing dependencies through Maven or Gradle.
Python Portion Existing Python testing benchmarks focus on test generation and coverage assessment, or provide reproducible real-world bugs for testing and debugging studies. These evaluation objectives differ from our focus on mocking artifact generation. We therefore construct a dedicated Python benchmark tailored to this task.
Construction Procedure
Following the aforementioned design, seven developers participated in constructing MockBench, with one serving as the lead reviewer and the remaining six responsible for benchmark construction. Each developer independently processed the assigned subjects—refining reference tests for Java and constructing parameterized reference suites for Python according to the established guidelines. The lead reviewer then examined all completed items to verify dependency selection, scenario design, and mock-artifact completeness, resolving any disputed or borderline cases. Finally, all reviewed tests were validated via execution: Java tests had to compile and pass, whereas Python suites were required to pass all parameterized test cases and meet the predefined MUT line-coverage threshold.
Experimental Design
RQ4 (Baseline Comparison): How do LLMs and coding agents perform relative to dedicated mock generation tools? Among existing mock-related techniques, StubCoder is the only comparable baseline: similar to LLMs and coding agents, it synthesizes stub behaviors from code and test context without executing real dependencies. Nevertheless, its native scope is limited to stub generation, whereas we tackle the holistic generation of mock objects, stubs, and mock assertions.
RQ5 (Resource Sensitivity): How does the operational time budget influence the effectiveness and workflow of coding agents? Coding agents can inspect projects, revise candidates, and perform validation during generation, while the time budget constrains the opportunities for these activities. We examine how final generation quality and workflows vary across budgets to understand the gains from additional time and the associated resource consumption.
Studied subjects
Studied Coding Agents To cover different agent designs, we select three coding agents: mini-SWE-agent, OpenCode, and Claude Code. mini-SWE-agent represents a lightweight agent scaffold with a minimal command-line interaction design, whereas OpenCode represents a full-featured open-source coding agent with repository-level interaction. Claude Code further represents a vendor-developed, full-featured coding agent designed for agentic software development workflows. To control for the influence of the underlying LLM, we configure all three coding agents with DeepSeek as the common backbone, enabling comparison across different agent workflows under the same model configuration.
RQ1: Executability
Executability across Coding Agents. Coding agents greatly improve test executability, especially on the harder Java benchmark. With the shared DeepSeek backbone, agent TPR on Java increases from 44.1% under standalone inference to 71.19–88.65%, an absolute gain of 27.1–44.6 percentage points. On Python, standalone DeepSeek already achieves a strong 86.5% TPR, leaving less room for improvement; here, agents achieve 79.18–95.95% TPR.
The remaining failures happen because agents exhaust their time budget, rather than generating code that fails to run. Once agents deliver a candidate, downstream compilation and test errors almost disappear: all three agents reach 100% CPR across both languages, with conditional TPR exceeding 99.3% on Java and reaching 100% on Python. Thus, the main barrier to executability is whether agents can finish code generation within their budget.
Implications
Implications for researchers: (1) As the first systematic study on mock artifact generation, this work reveals a fundamental pitfall: LLMs and coding agents synthesize mocks merely to satisfy tests, so test execution status alone is a misleading quality signal and should not serve as the sole benchmark for assessment. (2) By jointly measuring executability, behavioral fidelity, and interaction-fault detection, we expose behavioral deviations and silent losses in fault detection that passing tests conceal, and offer ready-to-use evaluation criteria for future research. (3) Scaling repair rounds and time budgets substantially boosts executability, yet yields no commensurate gain in behavioral fidelity, evidencing that coding agents optimize for crash avoidance rather than semantic correctness. This implies that future techniques should embed interaction contracts directly into generation objectives. (4) Our failure analysis distills 660 failures into ten error types spanning mock objects, stubs, and assertions, all of which survive behind passing tests; this taxonomy converts previously invisible failure modes into explicit optimization targets for faithfully reconstructing mock behaviors and enforcing interaction checks.
Implications for practitioners: (1) We construct MockBench, the first benchmark for mock quality evaluation, comprising 165 validated mock-related samples from real-world Java and Python projects that can be directly adopted for industrial evaluation. (2) Our experiments across six LLMs and three coding agents reveal their heterogeneous strengths: agents excel at executability, but such gains do not translate into behavioral fidelity or fault detection, providing evidence-based guidance for technique selection in mock-based testing. (3) The sensitivity analysis shows that enlarging agent time budgets improves executability only within a limited range and never behavioral fidelity. Practitioners should therefore treat passing tests as a necessary but insufficient checkpoint, invest in explicit behavioral verification rather than additional repair rounds, and consult our ten-type failure taxonomy to inspect the risks that remain concealed when generated tests pass.
Threats to Validity
Threats to external validity. Our evaluation is limited to mock artifact generation in Java and Python, excluding other PLs. However, given that Java and Python represent both statically- and dynamically-typed PLs, carry mature mocking ecosystems, and are widely used in practical development, the threat is minimal. Second, our findings may not generalize across all LLMs and agent architectures. These threats are also limited, as we tested diverse LLMs and coding agents of commercial, general, and code, as well as closed/open-source. Thus, experimental subjects are representative. As for the failure taxonomy, our extensive analysis spans two PLs, 660 distinct errors, four representative subjects (one LLM and three agents), and all three mocking artifacts. Hence, its generality threat is negligible.
Threats to internal validity. To prevent data leakage, MockBench features newly authored Python tests alongside Java tests augmented with additional mock artifacts. To reduce errors in manual construction, a lead reviewer examined all reference suites for dependency selection, scenario design, and mock-artifact completeness, followed by execution validation. Towards the subjectivity of failure analysis, each sample was independently inspected by two evaluators using a shared codebook developed through thematic analysis, with disagreements resolved through discussion and expert adjudication. Hence, the above threats are minimal.
Conclusion
This work presents MockBench, a bilingual benchmark for evaluating the generation of mock objects, stubs, and mock assertions. Through extensive experiments on six LLMs and three coding agents, we examine their capabilities in terms of executability, behavioral fidelity, and fault detection. The results show that coding agents significantly improve test executability, while passing tests may mask behavioral deviations and losses in interaction fault detection capability. Increasing the agents’ time budget can improve executability within an effective range, but incurs higher resource costs without a corresponding improvement in behavioral fidelity. Finally, our systematic failure analysis identifies ten error types across three categories of mock artifacts, providing concrete directions for future research and practical guidance for reviewing generated mock artifacts.


