Mockito - internal method call

user2057006 picture user2057006 · Feb 21, 2017 · Viewed 13.1k times · Source

I have a class called Availability.java and have two methods.

 public Long getStockLevelStage() {
     //some logic
      getStockLevelLimit();
    }

    public Long getStockLevelLimit() {
      String primaryOnlineArea = classificationFeatureHelper.getFirstFeatureName(productModel, FEATURE_CODE_PRODUCT_ONLINE_AREA_PRIMARY, language);
................
      return new Long();
    }

I'm writing a unit test class AvailabilityTest.java.

@RunWith(MockitoJUnitRunner.class)
public class AvailabilityTest {
  @InjectMocks
  private Availability availability = new Availability();

  @Test
  public void testGetStockLevelStage() {
    availability.getStockLevelStage();
  }
}

When I call availability.getStockLevelStage() method, it calls getStockLevelLimit() method. Is it possible to mock the internal method call?

In this case, I don't want getStockLevelLimit() to be executed, when getStockLevelStage() gets executes.

Please help.

Answer

Maciej Kowalski picture Maciej Kowalski · Feb 21, 2017

Try this:

@RunWith(MockitoJUnitRunner.class)
public class AvailabilityTest {
    @InjectMocks
    @Spy
    private Availability availability = new Availability();

    @Test
    public void testGetStockLevelStage() {
       Mockito.doReturn(expectedLong).when(availability).getStockLevelLimit();
       availability.getStockLevelStage();
    }
}

Here is an article I wrote on Mockito Spying if you need a further read.