Scrivio Interview library
ScenarioPrincipal6 min read · updated 12 November 2026

Mockito's inline mocking relies on agent-based bytecode changes, and the JDK is restricting dynamic agent loading. What long-term risk does this create for a large test estate, and how would you reduce it?

Every test that mocks a static, a final class or a JDK class depends on Mockito attaching an agent that rewrites bytecode, and the JDK is moving towards refusing agents that are loaded at runtime. For a large test estate the risk is that one JDK upgrade breaks thousands of tests at once. We reduce it by configuring Mockito as a -javaagent through the shared build convention now, shrinking static and construction mocking with seams such as Clock and small interfaces, tracking that usage with a target, and running the suite on new JDK versions early.

Background to this question

This is a question about risk management rather than about Mockito's API. A company with hundreds of services and tens of thousands of tests cannot fix a breaking change by hand in one sprint, so a senior engineer is expected to spot a slow-moving risk and turn it into a plan with measurable steps. In this answer, we will recap why inline mocking depends on agents, describe what could go wrong in a large estate and how big it can get, and then walk through four measures: the build flag, the design seams, tracking and early JDK testing.

1A Quick Recap of the Dependency

Mockito can mock static methods, final classes and constructors only through its inline mock maker. That maker attaches a Java agent, a component allowed to rewrite class bytecode, to the already running test JVM. Attaching an agent this way is called dynamic loading. Since JDK 21 (JEP 451), the JVM prints a warning when it happens, and the JDK team has said dynamic loading will be disallowed by default in a future release unless a flag is set.

Today nothing fails. That is precisely what makes it dangerous in a large organisation: a warning in thousands of build logs is invisible, and the change will arrive as part of a routine JDK upgrade that teams expect to be easy.

2What Could Go Wrong at Scale

Let us put numbers on it. Imagine 300 services and 60,000 tests. A quick search finds that 4,000 tests call mockStatic or mockConstruction, and another 6,000 mock final classes such as Kotlin classes, records or JDK types like java.time classes. If a future JDK refuses the dynamic agent, those 10,000 tests fail on the first build with the new JDK, not because the code is wrong but because the test infrastructure stopped working.

Then the real cost appears. The platform team wants to move to the new LTS for security support. Each service team now has to fix tests before it can upgrade, and the upgrade is blocked for the slowest team. There is a second, quieter risk: retransforming JDK classes is exactly what the JDK keeps restricting, so tests that mock JDK types can break even when the flag question is solved.

So the danger is not one broken test. It is a correlated failure across the whole estate that lands on the critical path of a platform upgrade.

Where the estate depends on instrumentation
Test patternNeeds the agentRisk on a future JDK
Mocks of interfaces and open classesnolow
Mocks of final classes and recordsyesfails if the agent cannot attach
mockStatic, mockConstructionyesfails if the agent cannot attach
Mocks or static mocks of JDK classesyescan break even with the agent

3Measure 1: Configure the Agent in the Shared Build Convention

The cheapest and fastest measure is to stop loading the agent dynamically. If the test JVM starts with -javaagent pointing at mockito-core, nothing is attached at runtime, the warning disappears, and the future default no longer matters. The key word is shared. We do not ask 300 teams to edit their builds; we put it once in the parent POM or the Gradle convention plugin that every service already uses.

XML
<!-- company parent POM, used by every service -->
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions><execution><goals><goal>properties</goal></goals></execution></executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>@{argLine} -javaagent:${org.mockito:mockito-core:jar}</argLine>
</configuration>
</plugin>

Notice the @{argLine} placeholder, which keeps flags added by coverage tools. After rolling it out, we can add a check in CI that fails the build if the log contains 'A Java agent has been loaded dynamically', so new projects cannot drift back.

4Measure 2: Introduce Seams Instead of Static Mocks

The flag removes the immediate risk, but most static mocking exists because the code has hidden dependencies. A seam is a place where we can swap behaviour without editing the code, typically a constructor parameter. The most common static mocks have well-known seams: the system clock becomes an injected java.time.Clock, UUID.randomUUID() becomes a small IdGenerator interface, and static helpers that call the network become an injected client.

Java
// Before: needs mockStatic(UUID.class) and mockStatic(Instant.class)
Order create() { return new Order(UUID.randomUUID(), Instant.now()); }
// After: plain constructor injection, no agent needed
Order create() { return new Order(ids.next(), Instant.now(clock)); }
// Test
var service = new OrderService(() -> FIXED_ID, Clock.fixed(T0, ZoneOffset.UTC));
assertEquals(FIXED_ID, service.create().id()); // passes

Each seam removes the need for instrumentation in every test that touches that code, and it makes the dependency visible to readers. We do not need to refactor everything; we target the classes that account for most static mocks.

5Measure 3: Track Usage and Set a Target

What we do not measure will grow back. A simple script or a static analysis rule (for example an ArchUnit test or a custom check in the code quality tool) counts calls to mockStatic and mockConstruction per repository, and mocks of final or JDK types if we can detect them. We publish the numbers on a dashboard and agree on a direction, such as no new static mocks in new code and a 50 percent reduction in a year.

The reason to set a target rather than a ban is practical. Legacy code sometimes has no seam yet, and a ban would push teams to worse workarounds. A target with visible progress lets teams choose the cheapest refactors first.

6Measure 4: Test on New JDKs Early

Finally, we stop discovering JDK changes on upgrade day. The platform team runs a nightly or weekly build of a representative set of services, and ideally the whole estate, on the next JDK version, including early-access builds. Failures go into a tracked backlog with owners. This turns a surprise into a forecast: we know months ahead how many tests would break and why.

Putting it together, the plan has a clear order. The build flag removes the near-term risk within weeks, seams and tracking reduce the dependency over the following year, and early JDK testing catches whatever we did not foresee.

Step throughReducing the risk across the estate
  1. Add -javaagent in the shared buildweeks; removes dynamic loading
  2. Fail CI on the dynamic agent warningstops drift in new projects
  3. Count mockStatic and mockConstructiondashboard per repository
  4. Refactor the top offenders to seamsClock, IdGenerator, small interfaces
  5. Build on the next JDK earlynightly, early-access builds

5 steps in order. Play them, or step through them one at a time.

7Follow-up questions

Why not just add -XX:+EnableDynamicAgentLoading everywhere?

It would work for now, but it keeps the estate on a behaviour the JDK is deliberately moving away from, and it says nothing about tests that mock JDK classes. Declaring the agent at startup is the intended route and costs the same effort.

Would switching to the subclass mock maker remove the risk?

It removes the agent, but every test that mocks a final class or a static then fails immediately. It is a useful end state for teams that have finished introducing seams, not a first step.

How do you convince teams to spend time on this?

By showing the numbers: how many of their tests would fail on the next JDK, and that the upgrade is a security requirement. A shared build change costs them nothing, and refactoring targets start with the classes that cause the most static mocks.

8Conclusion

In this answer, we saw that inline mocking of statics, finals and JDK classes depends on an agent that rewrites bytecode, and that the JDK is moving to disallow loading such agents at runtime. In a large estate this becomes a correlated failure that can block a JDK upgrade. We reduce the risk by adding -javaagent through the shared build convention now, replacing static mocks with seams such as Clock, tracking mockStatic and mockConstruction against a target, and running the suite on new JDKs early.

What to say in the interviewAbout 80 seconds aloud

Open with

The risk is a correlated failure. Every test that mocks a static, a final class or a JDK type relies on Mockito's inline mock maker, which attaches a Byte Buddy agent to the running JVM.

Then, if they want more

Since JDK 21 that dynamic loading prints a warning, and the JDK plans to disallow it by default. In a big estate that could mean thousands of tests failing on the first build with a new JDK, which blocks a security upgrade for everyone. I would handle it in four steps.

First, configure Mockito as a -javaagent in the shared parent POM or Gradle convention, keeping the existing argLine, and fail CI if the dynamic agent warning appears. That removes the near-term risk in weeks. Second, reduce the need for static mocking by introducing seams: an injected Clock instead of mocking LocalDate.now, an id generator interface instead of mocking UUID.

Third, measure mockStatic and mockConstruction per repository and set a target, like no new static mocks and half as many in a year. Fourth, build a representative set of services on the next JDK, including early-access builds, so we find breaking changes months before the upgrade.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Mockito's inline mocking relies on agent-based bytecode changes, and the JDK is...": https://scrivio-interview-library.netlify.app/java/mocking/224b2b19b6/