Testing Java Inheritance and Polymorphism with Mocked Base Classes

Writing tests for Java inheritance and polymorphism with mocked base classes starts with a useful question: which behaviour belongs to the test, and which belongs to production? A base class may own validation, retries, logging, or persistence, while subclasses supply a small variation. Mocking that base can make a focused unit test faster, but it can also hide the shared logic that gives the hierarchy its meaning.

Polymorphism adds another layer: the object selected at runtime determines which implementation executes. A test that stubs a method on a base type may pass while an inherited method, a super call, or a constructor side effect never runs. Mocking is justified by a more useful question: Which contract am I trying to verify, and at which boundary does the real implementation belong?

Australian engineering teams encounter this pattern in domains where change is costly. A Sydney payments company may protect a Java service with audit trails and repeatable deployment checks; a Brisbane health-tech product may need evidence that a notification followed the expected clinical workflow. Melbourne teams often describe a sensible engineering choice with plain phrases such as 'let's keep it simple', while distributed teams in Perth and Adelaide rely on asynchronous checks because one working day does not line up across the country. These constraints reward tests that are deterministic, explainable, and quick to diagnose.

Why Base-Class Mocks Change the Test

Mocking a base class changes the object under test, not just one dependency. Mockito creates a subclass-like proxy at runtime, so calls to eligible instance methods are intercepted and the real base constructor and body are bypassed. Unstubbed methods often return a default value such as null, false, or zero. That is convenient for a collaborator, but it can make a test assert only that a mock was called.

Polymorphism means the call site sees the declared type, while runtime dispatch still matters. If NotificationSender sender = new SmsSender(...) calls sender.send(...), a test of the sender's contract should distinguish between verifying the common send behaviour and verifying SMS-specific delivery. Replacing the whole hierarchy with a mock of NotificationSender removes that distinction unless the test explicitly selects a different boundary.

There is another trap with state in the base class. A constructor may create a repository, start a timer, or register a callback. A mock does not reproduce those effects. Conversely, a partial mock with real methods enabled can execute the base body and create surprising calls to unmocked collaborators. Treat a base-class mock as a deliberate test seam, not a universal substitute for testing the hierarchy.

A Polymorphic Design That Leaves a Test Seam

Start with a small design that makes the polymorphic contract visible. The following hierarchy has one shared operation and one implementation detail. NotificationSender owns the audit hook, while EmailSender decides how to deliver a message.

abstract class NotificationSender {
    private final AuditLog auditLog;

    protected NotificationSender(AuditLog auditLog) {
        this.auditLog = auditLog;
    }

    public void send(Message message) {
        auditLog.attempt(message.id());
        deliver(message);
        auditLog.success(message.id());
    }

    protected abstract void deliver(Message message);
}

final class EmailSender extends NotificationSender {
    private final EmailClient client;

    EmailSender(AuditLog auditLog, EmailClient client) {
        super(auditLog);
        this.client = client;
    }

    @Override
    protected void deliver(Message message) {
        client.send(message.address(), message.body());
    }
}

The common send method is the base-class contract, while deliver is the polymorphic extension point. A caller that accepts NotificationSender should work with any implementation. A unit test for the caller can therefore use a mock of the base type, whereas a test for EmailSender should exercise the real inherited send method and mock only the email client.

This split keeps the test's intent visible. It also prevents a passing mock-based test from being mistaken for evidence that audit logging, ordering, or failure handling works. The hierarchy remains simple enough to reason about, and each test has one clear owner for the behaviour it protects.

Mocking the Base Contract with JUnit and Mockito

In a JUnit 5 test, a mocked base type is usually declared with Mockito's @Mock annotation and injected into the class under test. Calling mock(NotificationSender.class) has the same effect. The mock can stand in for every concrete sender because the production code depends on the abstract contract.

final class NotificationService {
    private final NotificationSender sender;

    NotificationService(NotificationSender sender) {
        this.sender = sender;
    }

    void notifyCustomer(Message message) {
        sender.send(message);
    }
}

@ExtendWith(MockitoExtension.class)
class NotificationServiceTest {
    @Mock NotificationSender sender;
    NotificationService service;

    @BeforeEach
    void setUp() {
        service = new NotificationService(sender);
    }

    @Test
    void delegatesTheMessageToTheSender() {
        Message message = new Message("m-42", "alex@example.com", "ready");

        service.notifyCustomer(message);

        verify(sender).send(message);
        verifyNoMoreInteractions(sender);
    }
}

Use when for return values and doThrow or doAnswer for void methods. verify confirms the interaction, ArgumentCaptor lets the test inspect the selected message, and verifyNoMoreInteractions can reveal an accidental second call. These checks work well when the service owns the decision to invoke the sender; they do not prove what the sender does internally.

Keep the mock typed as the abstraction in the test. If the production field is NotificationSender, a test that declares EmailSender may accidentally rely on email-only methods and lose the value of polymorphic substitution. The same mock can support a contract test across several implementations, but each implementation still needs its own behavioural test.

Mocking a base class is particularly effective for asynchronous boundaries. A Java application may hand a message to a queue-backed sender in Brisbane while another worker consumes it later. A unit test can verify the publication call without waiting for a broker, network provider, or scheduled retry. The result is a fast specification of the handoff rather than a flaky integration test.

When a Child Calls super

The difficult case is a subclass that calls super. Java resolves super.method() against the direct superclass at compile time; it does not look up a Mockito mock created elsewhere. If a child calls super.calculate(...), mocking an unrelated BaseCalculator instance cannot intercept that call. This is a fundamental difference between substituting a collaborator and altering an inheritance chain.

Use a spy of the concrete child when an inherited, virtually dispatched method is the seam. For example, the child can call an inherited decorate method without overriding it. With the test in the same package, a spy can return a controlled value while the child's own format method remains under test:

class BaseWriter {
    String decorate(String body) {
        return "[" + body + "]";
    }
}

class CsvWriter extends BaseWriter {
    String format(String body) {
        return "csv:" + decorate(body);
    }
}

@Test
void addsTheCsvPrefixToTheBaseResult() {
    CsvWriter writer = spy(new CsvWriter());

    doReturn("{mocked}").when(writer).decorate("payload");

    assertEquals("csv:{mocked}", writer.format("payload"));
}

This technique is valid only when the call is virtual and reaches the inherited method through normal dispatch. If the child explicitly invokes super.decorate(...), an ordinary spy cannot replace that superclass implementation. In that situation, keep the real base behaviour and assert the composed result, or refactor the shared operation into a collaborator that can be mocked independently.

Partial mocks should be used sparingly. spy(new Child()) executes the real constructor and can create real collaborators, while mock(Base.class, CALLS_REAL_METHODS) still bypasses the base constructor and may leave fields unset. Prefer constructor injection, package-visible seams, or a small abstraction around super work. Then verify outcomes as well as interactions, especially when the base method has retries or validation.

Keeping Base-Class Tests Trustworthy

Before choosing a mock, ask what could fail in production and where the earliest useful observation is available. Use a base mock in these situations:

Choose a real base or a mocked collaborator in these situations:

In an Australian delivery team, these distinctions pay off during regulated change windows. A Sydney bank release may require evidence that a common validation step ran; a Melbourne platform team might call a suite with no hidden state a 'straightforward test'. Distributed teams can run the same checks in continuous integration while developers in Brisbane and Perth review failures asynchronously. Clear boundaries make those reviews faster because each failure points to a specific handoff rather than an unexplained mock. Documentation should name that seam, so usesTheSenderContract communicates more clearly than callsMock.

The rule to remember is simple: mock the base class when verifying a contract from the outside, and use the real base with mocked collaborators when verifying inherited behaviour. That boundary keeps Java polymorphism visible, makes failures explainable, and gives teams a test suite they can trust when a release reaches customers.