This is an issue when using mocking framework stubbing syntax to specify return values and creating a mock object directly as an argument to the return value specification method.

In Java with Mockito, this specifically refers to inlining the mock creation inside the thenReturn() method.

Why is this an issue?

Mocking frameworks use an internal state machine to track stubbing operations and validate that they are completed correctly. When you create a mock object inline within a return value specification, the framework registers the mock creation as a new event before it finishes recording the stubbing chain.

This sequence confuses the framework’s validation mechanism. The framework cannot properly detect whether the previous stubbing operation was finished or left incomplete. This breaks one of the framework’s key safety features: detecting unfinished stubbing.

Unfinished stubbing detection helps catch common mistakes like:

When inline mock creation prevents this detection, you may encounter confusing error messages in subsequent tests rather than in the test that contains the actual problem. This makes debugging significantly harder because the error location and the root cause are separated.

What is the potential impact?

When this pattern is used, the testing framework’s validation system is compromised. The immediate consequence is that developers lose the safety net that detects incomplete or improperly configured test doubles.

This can lead to:

In Mockito, this pattern specifically breaks the framework’s ability to detect unfinished stubbing, which is one of its key safety features.

How to fix it

Extract the mock object creation to a local variable, then pass that variable to thenReturn(). This ensures Mockito can properly track the stubbing sequence and validate that it is complete.

Code examples

Noncompliant code example

import static org.mockito.Mockito.*;

class MyTest {
    void testMethod() {
        MyClass mock = mock(MyClass.class);
        when(mock.foo()).thenReturn(mock(Foo.class)); // Noncompliant
    }
}

Compliant solution

import static org.mockito.Mockito.*;

class MyTest {
    void testMethod() {
        MyClass mock = mock(MyClass.class);
        Foo foo = mock(Foo.class);
        when(mock.foo()).thenReturn(foo);
    }
}

Resources

Documentation