I know I don't really need to know how Mockito does everything under the hood in order to be able to use it, but this has been perplexing me for a while so more than anything I'm curious to understand it. There are several Mockito methods that I can't understand how they could possibly work. One good example is:
OngoingStubbing<T> Mockito.when(T methodCall)
You can use this to do things like:
Object mockedObject = Mockito.mock(Object.class);
Mockito.when(mockedObject.toString()).thenReturn("super cool string");
System.out.println(mockedObject.toString());
This code would give the output:
super cool string
I understand how to use this, but I don't understand how this could possibly work. How does Mockito.when know what mock object and method we are concerned with? As far as I know, we aren't passing in mockedObject, we are passing in mockedObject.toString() which is a value of type String. I'm pretty sure that prior to setting up all of the "when/thenReturn" stuff, mockedObject.toString() just returns null. So why isn't this the same as doing:
Object mockedObject = Mockito.mock(Object.class);
mockedObject.toString();
Mockito.when(null).thenReturn("super cool string");
System.out.println(mockedObject.toString());
Obviously the second code segment doesn't make any sense, but it seems like the two code segments should be functionally equivalent.
EDIT: The two code segments actually are the same. See my answer to my own question below.