title: Mockito: mocking a method of same class called by method under test when using @InjectMocks
body: <p>I have a class I want to test that has several external dependencies, and a couple internal methods. I would like to write a test for <code>MethodA</code>, but <em>not</em> have Method A's internal call to <code>MethodB</code> to actually exercise <code>MethodB</code>. I'd like to mock/stub <code>MethodB</code> and return something specific instead. Usually I'd use <code>when/thenReturn</code> but it doesn't behave like I expect - it actually jumps into Method B while creating the mock itself.</p>
  
  <p><strong>MyService.java</strong></p>
  
  <pre><code>@Service
  public class MyService {
  
    @Autowired
    private ServiceA serviceA;
  
    @Autowired
    private ServiceB serviceB;
  
      public SomeObject methodA() {
        // some logic using serviceA.method and serviceB.method that creates "output"
        SomeObject someObject = methodB(output);
        return someObject;
      }
  
      public SomeObject methodB(SomeObject someObject) {
        // deep mysteries done here to someObject
        return someObject 
      }
  }
  </code></pre>
  
  <p><strong>MyServiceTest.java</strong></p>
  
  <pre><code>public class MyServiceTest {
  
    @Mock
    private ServiceA serviceA;
  
    @Mock
    private ServiceB serviceB;
  
    @InjectMocks
    private MyService myService;
  
    @Before
    public void setUp() throws Exception {
      MockitoAnnotations.initMocks(this);
    }
  
    @Test
    public void methodATest() {
      when(serviceA.method()).thenReturn(stuff);
      when(serviceB.method()).thenReturn(otherStuff);
  
      // here is what I would like to do
      when(myService.methodB()).thenReturn(mockedSomeObject); //&lt;- doesn't work
  
      assertThat(myService.methodA().getSomeObjectProperty())
          .isEqualTo("property");
    }
  }
  </code></pre>
  
  <p>I've looked at solutions that manually mock the <code>MyService</code> class with <code>Mockito.mock(MyService.class)</code>, but (as the above example is obviously contrived) my actual class has quite a few external dependencies and I'd prefer a solution that still allows me to mock the service using <code>@Mock</code> for the <code>@Autowired</code> dependencies and <code>@InitMocks</code> for the class under test, unless it's simply not possible.</p>
  
  <p>I've tried:  </p>
  
  <pre><code>Mockito.doReturn(mockedSomeObject).when(myService.methodB(any(SomeObject.class));
  </code></pre>
  
  <p>but that also steps into MethodB when creating the mock for that method, which shouldn't be happening.</p>
  
  <p>Thanks in advance for the help!</p>