Unit testing Java anonymous and inner classes

Java lets you tuck a class inside another one, and it does so in several distinct ways: an anonymous class written inline at the point of use, a local class declared inside a method, a member inner class that keeps a reference to its enclosing instance, and a static nested class that does not. Each form compiles to its own class file — Outer$1.class, Outer$Inner.class — and each behaves slightly differently when you try to test it. Learn more about Tech Needs.

The trouble is rarely the syntax itself, it is the invisibility. A callback registered as an anonymous class cannot be handed back to a test without a seam. A member inner class cannot be instantiated without an enclosing object, which may drag half a dependency graph behind it. And because these classes live in numbered or dollar-named class files, they are easy to overlook in coverage reports, so a suite can look complete while the trickiest branch in the system sits unexercised. Learn more about Pliantalliance.org.

What follows is a practical routine: how to recognise which nested type you are holding, how to capture an anonymous instance without changing production behaviour, how to satisfy the enclosing instance requirement, and how to assert on collaborators invoked from inside an inner class. The examples use JUnit 5, AssertJ and Mockito, with a nod to Spock where Groovy teams are involved.

Where nested classes hide from your tests

Start by opening your coverage report and looking for the odd entries. Alongside ShippingCalculator.class you will usually find ShippingCalculator$1.class or ShippingCalculator$Parcel.class. JaCoCo instruments them and they do contribute to bundle figures, but class-level dashboards often treat them as noise, and filters that exclude synthetic or bridge methods can quietly drop the bodies of anonymous classes altogether. Mutation testing exposes the same blind spot more sharply: PIT frequently reports surviving mutants inside nested classes, because the tests assert on the outer result and never pin down the branch that actually holds the logic.

There is a second, quieter problem: identity. Two instances of an anonymous class are not equal unless the class overrides equals, so assertThat(listener).isEqualTo(expected) fails in ways that look like a production bug. isSameAs tells you the reference was handed back, but the interesting assertion is usually about state or behaviour, which means you need somewhere to put the instance.

Nested type Created where Keeps an outer reference Holds its own state Practical seam
Anonymous class Inline at the use site No implicit one; captures locals Yes, through its fields A factory or supplier that hands the instance back
Local class Inside a method body No implicit one Yes Return it from the method or extract it
Member inner class In the body of another class Yes, through this$0 Yes Build a cheap enclosing instance, or make it static
Static nested class In the body of another class No Yes Instantiate directly and assert normally
Lambda Inline at the use site No implicit one Only through captured locals Assert on the effect, not the function object

Pick the row that matches your code and choose the seam on the right. For the anonymous class, capture the instance. For the member inner class, remove the enclosing instance tax. The rest follows from that decision.

Knowing which nested class you are looking at

Reflection gives you an exact answer rather than a guess. Class.isAnonymousClass(), isLocalClass() and isMemberClass() identify the shape, while getEnclosingClass() and getEnclosingMethod() tell you where it came from. getDeclaredClasses() on the outer class lists every nested type it owns, which is a quick way to audit a codebase and spot the ones with no test at all.

Two syntax details catch people out. First, an anonymous class may extend a class as well as implement an interface, but it cannot declare a constructor, so initialisation happens through captured variables or an instance initialiser block. Since Java 16 the restriction on static members was relaxed, though most code still keeps anonymous bodies stateless and side-effect free. Second, an anonymous class has no implicit handle on the enclosing object; if it needs an outer field it must say so explicitly with OrderValidator.this.warnings.

class OrderValidator {
    private final List<String> warnings = new ArrayList<>();

    Runnable preCheck() {
        String reference = orderReference();   // must be final or effectively final
        return new Runnable() {
            @Override
            public void run() {
                warnings.add("Reference " + reference + " needs review");
            }
        };
    }
}

That warnings.add(...) line does not compile as written; it becomes OrderValidator.this.warnings.add(...). It is a useful reminder that the anonymous body is a real class with real access rules, and a test that wants to observe it needs a way in.

Capturing an anonymous class in a test

The cleanest seam is usually a factory that returns the interface rather than the implementation. Injecting a Supplier<Listener> keeps the production class testable and leaves the anonymous class exactly where it belongs.

class NotificationService {
    private final Supplier<Listener> listenerFactory;

    NotificationService(Supplier<Listener> listenerFactory) {
        this.listenerFactory = listenerFactory;
    }

    void notifyAll() {
        listenerFactory.get().onEvent("shipment-ready");
    }
}

The test then supplies a mock or a recording stub and asserts on the interaction:

@Test
void notifiesWithTheEventPayload() {
    var listener = mock(Listener.class);
    var service = new NotificationService(() -> listener);

    service.notifyAll();

    verify(listener).onEvent("shipment-ready");
}

When you cannot inject a supplier, use a holder. The anonymous class registers itself in a list that the test owns, which costs almost nothing in production code:

List<Listener> captured = new ArrayList<>();
Listener listener = new Listener() {
    @Override public void onEvent(String event) { captured.add(this); }
};

From there, AssertJ reads nicely: assertThat(captured).hasSize(1) followed by assertions on captured state. For arguments rather than instances, an ArgumentCaptor captures the values passed across the boundary — handy when the callback formats a payload, for instance producing a GST-inclusive total of $120 from a $100 line at the Australian rate of twenty per cent.

Paying the enclosing instance tax

A member inner class carries an implicit reference to its outer instance, which means new ShippingCalculator(rates).new Parcel() is the only way to build one. That single expression explains most of the friction teams report with nested classes: the test now needs a valid outer object, and if that constructor opens a database client, loads configuration from AWS or registers a shutdown hook, the unit test quietly becomes an integration test.

class ShippingCalculator {
    private final RateTable rates;

    ShippingCalculator(RateTable rates) {
        this.rates = rates;
    }

    class Parcel {
        int cost(int grams) {
            return rates.costFor(grams);
        }
    }
}

Three ways out. Make the nested class static if it does not need the outer state, pass a lightweight outer instance, or move the shared data into a small record and hand that to both types. Converting Parcel to static is often a one-word change with a meaningful payoff, since it removes the implicit this$0 field and the retention of the whole outer object that comes with it.

Access rules matter here too. Since nest-based access control arrived in Java 11, a test class in the same package still cannot reach private members of production code directly, so either expose a package-private seam or step through the public entry point. Local classes declared inside a method are reachable through getEnclosingMethod() and can even be instantiated reflectively, but testing them through the public method almost always produces a better contract.

Mocking collaborators called from inside

Mockito's inline mock maker has been the default since version five, so final classes and final methods can be stubbed without ceremony. That means extracting an anonymous class into a named inner class is no longer blocked by mockability, which removes the usual excuse for leaving awkward logic inline.

The call stack does not affect verification. Whether the dependency is invoked from the outer class or from a nested one, verify(rateTable).costFor(1200) works exactly the same way.

@Test
void capturesTheParcelReference() {
    var rates = mock(RateTable.class);
    var parcel = new ShippingCalculator(rates).new Parcel();

    parcel.cost(1200);

    verify(rates).costFor(1200);
}

The failure mode to watch for is a verification that never fires because the callback was registered but never triggered. If an inner class only calls its dependency when the consumer invokes a listener, the test must invoke that listener too, otherwise the assertion passes vacuously.

Groovy teams have a lighter alternative. In a Spock specification, def rates = Mock(RateTable) and 1 * rates.costFor(1200) >> 42 express the same contract with less ceremony, and Groovy closure coercion to a single-abstract-method interface reads naturally for callback-driven code. Before adding another mocking library to the build, it is worth pausing to audit your tech needs against what the team already maintains.

From a local check to an overnight pipeline

Local coverage is only half the story. Australian teams are spread across time zones, and a pipeline triggered late in Sydney or Brisbane continues running through the evening in Perth, where the clocks sit two hours behind. Splitting the Gradle test task and enabling JUnit 5 concurrent execution keeps feedback inside a coffee break, provided nested class tests do not share mutable static state — remember that anonymous instances are distinct objects, so assertions on captured state are safe while assertions on shared singletons are not.

The commercial pressure is real as well. Sydney hosts Atlassian, a large share of the country's payment and platform engineering, and the Australian Securities Exchange runs trade-matching code whose every branch is audited. A characterisation test that pins down an anonymous fallback strategy is often cheaper than the incident it prevents. In Canberra, federal agencies working to the Australian Government Digital Service standard inherit older systems built around exactly these nested classes, and ATO platforms are a familiar example; writing the characterisation tests before a refactor is what makes the rewrite safe. Brisbane and Melbourne teams, clustered around the Queensland public sector and Melbourne's Docklands precinct, tend to hit the same pattern, with an inner class holding a rule that no one owns.

Aligning those tests with the people who own the rules takes more than a green build. The kind of collaboration described on the Pliant Alliance site is where a branch on GST-inclusive pricing gets agreed with the business rather than guessed at by a developer.

The practical takeaway is simple: treat every nested class as a contract in its own right. Name it or capture it, give it a seam that costs nothing, and assert on what it does rather than on the object it happens to be.