Search code examples
androidmockitojunit4

Mock method called inside testing method in same class


 public class MyClass {

   public int result(){
     int result = calculate(new ValueProvider());
          return result;
      }

   public int calculate(ValueProvider provider){
            return provider.getSalary();
      }

}

public class ValueProvider {

    public int getSalary(){
        return 10000000;
    }
}

I need to test method result(), but have to mock second method calculate which should return default value.


Solution

  • Use a Mockito spy to create a partial mock.

    For example:

    public class TestMyClass {
    
        @Test
        public void aTest() {
            MyClass spy = Mockito.spy(MyClass.class);
    
            // this will cause MyClass.calculate() to return 5 when it 
            // is invoked with *any* instance of ValueProvider
            Mockito.doReturn(5).when(spy).calculate(Mockito.any(ValueProvider.class));
    
            Assert.assertEquals(123, spy.result());
        }
    }
    

    In this test case the invocation on calculate is mocked but the invocation on result is real. From the docs:

    You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).