title: Mockito testing class with dependency created in constructor
body: <p>I am trying to write a test for legacy code that is looking like this: </p>
  
  <pre><code>public class TestedClass {
      private A a = StaticFactory.createA();
      private B b = StaticFactory.createB();
      // No default constructor
      // code using A and B classes
  }
  </code></pre>
  
  <p>As far as my understanding of Mockito goes, I know that I can not mock static methods, however I know that I can use a little trick and externalize creation of this object to package-private methods like this: </p>
  
  <pre><code>public class TestedClass {
  
      private A a;
      private B b;
  
      TestedClass() {
          a = createA();
          b = createB();
      }
  
      A createA() {
          return StaticFactory.createA();
      }
  
      B createB() {
          return StaticFactory.createB();
      }
  
      // code using A and B classes
  }
  </code></pre>
  
  <p>But using this construction I am unable to create spy of <code>TestedClass</code>, it has to be already a spy to use <code>doReturn(..)</code> constructions so test like this won`t work: </p>
  
  <pre><code>public class TestedClassTest {
  
      TestedClass testedClass;
  
      A mockA;
      B mockB;
  
      @Before
      public void setUp() {
          mockA = mock(A.class);
          mockB = mock(B.class);
  
          testedClass = Mockito.spy(new TestedClass());
  
          doReturn(mockA).when(testedClass).createA();
          doReturn(mockB).when(testedClass).createB();   
      }
  }
  </code></pre>
  
  <p>Is there any other way to change behaviour of <code>createA</code> and <code>createB</code> methods that are getting fired in constructor to ensure that I have mocks instances?</p>
  
  <p>In this case, <code>StaticFactory.createA()</code> is run and it is throwing exception (just under tests), unabling me to finish initialization of tests.</p>
  
  <pre><code>Running pl.tbawor.TestedClassTest
  Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.168 sec &lt;&lt;&lt; FAILURE!
  shouldTestSomething(pl.tbawor.TestedClassTest)  Time elapsed: 0.114 sec  &lt;&lt;&lt; ERROR!
  java.lang.NullPointerException
          at pl.tbawor.StaticFactory.createA(TestedClass.java:32)
          at pl.tbawor.TestedClass.createA(TestedClass.java:14)
          at pl.tbawor.TestedClass.&lt;init&gt;(TestedClass.java:9)
          at pl.tbawor.TestedClassTest.setUp(TestedClassTest.java:26)
  </code></pre>
  
  <p><em>My goal is to avoid running original methods for creation <code>A</code> and <code>B</code> objects to prevent exception from being thrown.</em> </p>
  
  <p>Also as this is legacy project, I am unable to add any additional libraries (PowerMock). </p>
  
  <p>I`ll add that TestingClass modification should be as little as possible. </p>