Latesh Mumbarkar
Latesh Mumbarkar

Reputation: 1

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.

Upvotes: 0

Views: 5512

Answers (1)

glytching
glytching

Reputation: 47905

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).

Upvotes: 3

Related Questions