Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 504
user2057006 Avatar asked Feb 21 '17 15:02

user2057006


People also ask

How do you call a real method in Mockito?

To call a real method of a mock object in Mockito we use the thenCallRealMethod() method.

What is the difference between doReturn and thenReturn?

One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test. I strongly recommend only using doReturn/when .

How do you mock a private method in JUnit?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.

How do you verify a method is called in Mockito?

Mockito verify() simple example It's the same as calling with times(1) argument with verify method. verify(mockList, times(1)). size(); If we want to make sure a method is called but we don't care about the argument, then we can use ArgumentMatchers with verify method.


1 Answers

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.

like image 138
Maciej Kowalski Avatar answered Sep 20 '22 16:09

Maciej Kowalski