title: How do I mock an implementation class?
body: <p>I have something like this:</p>
  
  <pre><code>public interface SomeInterface {
      public String someMethod(String someArg1, String someArg2);
  }
  
  public class SomeInterfaceImpl {
  
      @Override
      public String someMethod(String someArg1, String someArg2) {
          String response;
  
          // a REST API call which fetches response (need to mock this)
  
          return response;
      }
  }
  
  public class SomeClass {
  
      public int execute() {
  
          int returnValue;
  
          // some code
  
          SomeInterface someInterface = new SomeInterfaceImpl();
          String response = someInterface.someMethod("some1", "some2");
  
          // some code
  
          return returnValue;
      }
  }
  </code></pre>
  
  <p>I want to test the <code>execute()</code> method in <code>SomeClass</code> using JUnit. Since <code>someMethod(String someArg1, String someArg2)</code> calls a REST API, I want to mock <code>someMethod</code> to return some predefined response. But somehow, the real <code>someMethod</code> gets called instead of returning the predefined response. How do I make it work?</p>
  
  <p>Here is what I have tried using Mockito and PowerMockito:</p>
  
  <pre><code>@RunWith(PowerMockRunner.class)
  @PrepareForTest({ SomeInterface.class, SomeInterfaceImpl.class, SomeClass.class })
  public class SomeClassTest {
  
      @Test
      public void testExecute() {
          String predefinedResponse = "Some predefined response";
          int expectedReturnValue = 10;
  
          SomeInterfaceImpl impl = PowerMockito.mock(SomeInterfaceImpl.class);
          PowerMockito.whenNew(SomeInterfaceImpl.class).withAnyArguments().thenReturn(impl);
          PowerMockito.when(impl.someMethod(Mockito.any(), Mockito.any())).thenReturn(predefinedResponse);
  
          SomeClass someClass = new SomeClass();
          int actualReturnValue = someClass.execute();
          assertEquals(expectedReturnValue, actualReturnValue);
        }
  }
  </code></pre>