user2057006
user2057006

Reputation: 647

Mockito - internal method call

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.

Upvotes: 11

Views: 25234

Answers (2)

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

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.

Upvotes: 14

davidxxx
davidxxx

Reputation: 131346

if getStockLevelLimit() has not to be executed during your test, it means in a some way you want to mock the class under test.
Doing it reduces the relevance and the authenticity of the behavior tested.

You should mock dependencies and not internal methods of the tested class.
I suppose you don't want to execute getStockLevelLimit() because it uses external dependency that you want to isolate or something of similar.
So you should mock and isolate which is behind getStockLevelLimit() and that doesn't make directly part of the Availability class.

Upvotes: 10

Related Questions