What happens when `when()` is invoked in Mockito?

What happens when when() is invoked in Mockito?

Given the following mockito when() statement:

when(mock.method()).thenReturn(someValue);

How does Mockito create a proxy for the mock, considering that mock.method() is executed before being passed to when()?

I assume this involves some CGLib or bytecode manipulation, but I’d like to understand the technical details of how this works.

Use Mockito.when() with doReturn() Instead :

Since when(mock.method()) evaluates before when(), an alternative is to use doReturn(), which avoids premature execution:

doReturn(someValue).when(mock).method();

This ensures method() is not executed before stubbing.

If the method returns another mock, you can enable deep stubbing:

MockedType mock = mock(MockedType.class, RETURNS_DEEP_STUBS);
when(mock.method()).thenReturn(someValue);

This prevents NullPointerException when chaining methods.

If mock.method() has internal logic you want to preserve, use a spy:

MockedType spy = spy(new MockedType());
doReturn(someValue).when(spy).method();

Unlike mocks, spies allow partial stubbing while keeping real behavior.