Prasant
Prasant

Reputation: 51

How to mock a particular method of a spring bean

I have a spring bean with multiple APIs. Mocking the bean doesn't serve my purpose as I would like to verify fetchFromDb() called only once on multiple calls to getCachedData() with the same input. This is to make sure the result is cached.

Is it possible to mock fetchFromDb() on bean 'market' while calling getCachedData()?

Sample Class

@Configuration("market")
public class AllMarket {

@Autowired
private CacheManager cachedData;

public boolean getCachedData(LocalDate giveDate) {
   //check if it exists in cache
   if(Objects.nonNull(checkCache(giveDate)) {
      return checkCache(giveDate);
   }
   //fetch from database
   boolean bool = fetchFromDb(givenDate);
   cacheData(giveDate, bool);
   return bool;
}
public boolean checkCache(LocalDate giveDate) {
   return cacheManager.getData(givenDate); 
}
public boolean fetchFromDb(LocalDate givenDate) {
  //return the data from database
} 
public void cacheData(LocalDate givenDate, boolean bool) {
   cacheManager.addToCache(givenDate, bool);
}

}

Upvotes: 0

Views: 1126

Answers (2)

Dmitry Khamitov
Dmitry Khamitov

Reputation: 3276

You can use Mockito.spy() for this kind of test. In this case you should spy your AllMarket instance and stub fetchFromDb. At the end you can Mockito.verify that fetchFromDb was called exactly once. It will look something like this:

AllMarket spy = spy(allMarket);
when(spy.fetchFromDb(givenDate)).thenReturn(true); //you have boolean as a return type
...
verify(spy, times(1)).fetchFromDb(givenDate);

For more information, you can see Official Mockito doc

Upvotes: 2

Romas Augustinavičius
Romas Augustinavičius

Reputation: 443

Maybe mockito argument captor could asist you. It lets you to capture method input and how many times method was called, also may other functions. Please check https://www.baeldung.com/mockito-annotations.

Upvotes: 0

Related Questions