title: Creating a thread with a Mockito mocked Runnable
body: <p>I have a class that implements <code>Runnable</code> called <code>DoThingInALoop</code>. It is given to a second class that will create a thread out of it, call this thread <code>Boss</code>. The <code>Boss</code> can tell the runnable to quit and let the thread terminate. Later, it can create a new thread with that same <code>DoThingInALoop</code>. </p>
  
  <p>When I am writing unit tests for the <code>Boss</code> I want to mock the <code>DoThingInALoop</code> because it is not the object under test. However, <code>DoThingInALoop</code> extends a class <code>Loop</code> and the code for <code>Loop</code> is actually being executed in the thread spawned by the <code>Boss</code>. That code of course runs into <code>NullPointerException</code>s because none of the member variables are set, because the object is mocked.</p>
  
  <p>How can I prevent Java's <code>Thread</code> from "seeing through" the mock?</p>
  
  <pre><code>public class Loop implements Runnable {
      private final Object member = new Object();
      public final void run() {
          // This code runs, but it shouldn't
          synchronized (member) { // Throws NPE
              ...
          }
          // Hook for subclasses
          try {
              subclassRun();
          } finally {
              // Mandatory cleanup (unrelated to question)
          }
  }
  
  public class DoThingInALoop extends Loop {
      public void subclassRun() { ... }
      public void stopDoingThingsInALoop() {
          // Set instance member that on next loop iteration signals thread to return
      }
  }
  
  public class Boss {
      private final DoThingsInALoop toBeMocked;
      public Boss(final DoThingsInALoop toBeMocked) {
          this.toBeMocked = toBeMocked;
      }
      public void start() {
          // Simplified
          new Thread(toBeMocked).start();
      }
      public void stop() {
          toBeMocked.stopDoingThingsInALoop();
      }
  }
  
  
  public class TestClass {
      @Test
      public void aTest() {
          // Setup Mocks
          DoThingsInALoop mockLoop = mock(DoThingsInALoop.class);
          Boss boss = new Boss(mockLoop);
  
          // Run test
          boss.start();
  
          // After the above line runs, a new thread is started and
          // the run() method of `Loop` executes until the NPE
          // is hit when it attempts to access a member variable
          // which is of course not set because it is a mocked object
  
          ...
      }
  }
  </code></pre>