title: Mocking Objects Created Inside method Under test
body: <p>I have a class which I would like to test.Whenever possible I would do dependency injections for that class which depends on object of other classes.But,I ran into a case where I would like to mock the object without restructuring the code and not appling DI.</p>
  
  <p>Here is the class under test:</p>
  
  <pre><code>public class Dealer {
  
      public int show(CarListClass car){
          Print print=new Print();
  
          List&lt;String&gt; list=new LinkedList&lt;String&gt;();
  
          list=car.getList();
          System.out.println("Size of car list :"+list.size());
  
          int printedLines=car.printDelegate(print);
          System.out.println("Num of lines printed"+printedLines);
  
          return num;
      }
  }
  </code></pre>
  
  <p>and my test class for this is:</p>
  
  <pre><code>public class Tester {
      Dealer dealer;
  
       CarListClass car=mock(CarListClass.class);  
       List&lt;String&gt; carTest;
       Print print=mock(Print.class);
  
      @Before
      public void setUp() throws Exception {
          dealer=new Dealer();
          carTest=new LinkedList&lt;String&gt;();
          carTest.add("FORD-Mustang");
          when(car.getList()).thenReturn(carTest);
          when(car.printDelegate(print)).thenReturn(9);
      }
  
      @Test
      public void test() {
  
          int no=dealer.show(car);
          assertEquals(2,number);//not worried about assert as of now
  
      }
  }
  </code></pre>
  
  <p>I couldn't figure out a solution to mock the print object inside the Dealer class.Since,I mock it in the Test class,but it gets created in the method under test.I did my research,but couldn't find any good resource.</p>
  
  <p>I know taking Print object creation out of this method and Injection the object is the better way,but I would like to test the code as it is ,with the print object being created inside the method.Is there any way to do this</p>