title: How does Mockito.when work under the hood
body: <p>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:</p>
  
  <pre><code>OngoingStubbing&lt;T&gt; Mockito.when(T methodCall)
  </code></pre>
  
  <p>You can use this to do things like:</p>
  
  <pre><code>Object mockedObject = Mockito.mock(Object.class);
  Mockito.when(mockedObject.toString()).thenReturn("super cool string");
  System.out.println(mockedObject.toString());
  </code></pre>
  
  <p>This code would give the output:</p>
  
  <pre><code>super cool string
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>Object mockedObject = Mockito.mock(Object.class);
  mockedObject.toString();
  Mockito.when(null).thenReturn("super cool string");
  System.out.println(mockedObject.toString());
  </code></pre>
  
  <p>Obviously the second code segment doesn't make any sense, but it seems like the two code segments should be functionally equivalent.</p>
  
  <p>EDIT:
  The two code segments actually <strong>are</strong> the same. See my answer to my own question below.</p>