title: Mockito - Mocking Concrete Classes
body: <p>Given the following code:</p>
  
  <pre><code>    LinkedList list = mock(LinkedList.class);
      doCallRealMethod().when(list).clear();
      list.clear();
  </code></pre>
  
  <p>by executing this test, a NullPointerException is thrown from first line in LinkedList#clear: </p>
  
  <pre><code>public void clear() {
      Entry&lt;E&gt; e = header.next;
      while (e != header) {
          Entry&lt;E&gt; next = e.next;
          //Code omitted. 
  </code></pre>
  
  <p>but <strong>header</strong> has been instantiated before: </p>
  
  <pre><code>private transient Entry&lt;E&gt; header = new Entry&lt;E&gt;(null, null, null);
  </code></pre>
  
  <p>Could someone please explain what's happening during mock creation?</p>
  
  <p><strong>#######  UPDATE.  ######</strong></p>
  
  <p>Having read all answers especially Ajay's one, I looked into Objenesis source code and find out that it's using Reflection API to create the proxy instance (through CGLIB) and therefore bypassing all constructors in the hierarchy until java.lang.Object.</p>
  
  <p>Here is the sample code to simulate the issue:</p>
  
  <pre><code>public class ReflectionConstructorTest {
  
      @Test
      public void testAgain() {
  
          try {
              //java.lang.Object default constructor
              Constructor javaLangObjectConstructor = Object.class
                      .getConstructor((Class[]) null);
              Constructor mungedConstructor = ReflectionFactory
                      .getReflectionFactory()
                      .newConstructorForSerialization(CustomClient.class, javaLangObjectConstructor);
  
              mungedConstructor.setAccessible(true);
  
              //Creates new client instance without calling its constructor
              //Thus "name" is not initialized.
              Object client = mungedConstructor.newInstance((Object[]) null);
  
              //this will print "CustomClient" 
              System.out.println(client.getClass());
              //this will print "CustomClient: null". name is null.
              System.out.println(client.toString());
  
          } catch(Exception e) {
              e.printStackTrace();
          }
      }
  }
  
  
  class CustomClient {
      private String name;
  
      CustomClient() {
          System.out.println(this.getClass().getSimpleName() + " - Constructor");
          this.name = "My Name";
      }
  
      @Override
      public String toString() {
          return this.getClass().getSimpleName() + ": " + name;
      }
  }
  </code></pre>