首页 > 解决方案 > 如何模拟spring bean的特定方法

问题描述

我有一个带有多个 API 的 spring bean。模拟 bean 并没有达到我的目的,因为我想验证 fetchFromDb() 在多次调用 getCachedData() 时只调用一次相同的输入。这是为了确保结果被缓存。

是否可以在调用 getCachedData() 时在 bean 'market' 上模拟 fetchFromDb()?

样本类

@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);
}

}

标签: springjunitmockito

解决方案


您可以Mockito.spy()用于此类测试。在这种情况下,您应该监视您的AllMarket实例和存根fetchFromDb。最后,您可以Mockito.verifyfetchFromDb调用一次。它看起来像这样:

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

有关更多信息,您可以查看官方 Mockito 文档


推荐阅读