spring - 如何模拟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);
}
}
解决方案
您可以Mockito.spy()
用于此类测试。在这种情况下,您应该监视您的AllMarket
实例和存根fetchFromDb
。最后,您可以Mockito.verify
只fetchFromDb
调用一次。它看起来像这样:
AllMarket spy = spy(allMarket);
when(spy.fetchFromDb(givenDate)).thenReturn(true); //you have boolean as a return type
...
verify(spy, times(1)).fetchFromDb(givenDate);
有关更多信息,您可以查看官方 Mockito 文档
推荐阅读
- mysql - 是否可以对 MySQL 中的组进行子计数
- r - R帮助:保持一个变量不变的F统计回归测试
- reporting-services - SQL Reporting Services:链接的报表参数未更新
- go - 指针接收器中未解析的类型
- php - PHP - 像这样获取帖子:变量中的联系人[id]
- node.js - 如何禁止添加具有相同objectId的mongodb中已经存在的较小数字?
- javascript - Fetch 是空的 Redux Saga
- xml - Excel 到 XML xsd:date 模式格式,xsd 的“what if”语句?
- python - 烧瓶选择表单未在请求中发送完整的选项值
- mysql - 从表中获取记录并将它们放在新表中