title: How to mock an object that is already being instantiated within the code of the class to be tested and write stubs for it?
body: <p>The class I need to test will look somewhat similar to this. I am not writing the actual class here.</p>
  
  <pre><code>public class Client {
  
  private String country;
  private ConnectionImpl conn;
  
  public Client (String country){
      this.country = country;
  }
  
  private ConnectionImpl createConnection() {
    SetConnectionImpl impl = new SetConnectionImpl() {
      public String getFirstName() {
        return "Some value";
      }
      public String getLastName() {
        return "Some value";
      }
      public String getAddress() {
        return "Some value";
      }
      public String getPhoneNumber() {
        return "Some value";
      }};
    return new ConnectionImpl("", "", "", "", impl);
  }
  
  public String letsDoSomeWork(String requestObject) {
    final ConnectionImpl impl = createConnection();
    String letsHaveSomeResponse = 
    impl.methodTobeStubbed(requestObject);
    return letsHaveSomeResponse;
  }
  }
  </code></pre>
  
  <p>Now the test class that I have written will look like this. I am using mockito to write stubs.</p>
  
  <pre><code>@Runwith(MockitoJunitRunner.class)
  public class ClientTest {
  @Mock
  ConnectionImpl impl;
  
  private Client client;
  @Before()
  public void initialize() {
  client = new Client("India");
  }
  
  @Test
  public void testLetsDoSomework_ShouldReturnString() {
  String request = "request";
  when(impl.methodTobeStubbed(request)).thenReturn("Response");
  String letsHaveSomeResponse = client.letsDoSomeWork(request);
  //Now I will make Assertions
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Unfortunately this stubbing doesn't work and my assumption is that since the class to be tested is internally creating an "impl" object, the mock object that I am creating here is not being considered. So in the end the code is entering the "impl" class which it should not.</p>
  
  <pre><code>when(impl.methodTobeStubbed(request)).thenReturn("Response");
  </code></pre>