模拟测试缓存

问题描述

我正在尝试使用 mockito 测试我的缓存层。

我按照说明使用咖啡因 here

基本上,我有这个......

@Service
class Catalog {

  @Autowired
  Db db;

  @Cachable
  public List<Item> getItems() {
    // fetch from db
    db.someDbMethod();
  }
}

@Configuration
@EnableCaching
class CatalogConfig {
  @Bean
  public CacheManager cacheManager() {
    return new caffeineCacheManager();
  }
  @Bean
  public Db db() {
     return new Db();
  }
}
// properties as in documentation etc

效果很好,方法被缓存并且工作正常。

我想添加一个测试来验证数据库调用只被调用一次,我有类似的东西但它不起作用:

public class CatalogTest {

     @Mock
     Db db;

     @InjectMocks
     Catalog catalog;

     // init etc

     @Test
     void cache() {
       catalog.getItems();
       catalog.getItems();
       verify(db,times(1)).someDbMethod(); // fails... expected 1 got 2
     }
     // Some other passing tests below
     @Test
     void getItems() {
       assertNotNull(catalog.getItems()); // passes
     }
}

我尝试了 @Profile/@ActiveProfileConfig/ContextConfiguration 等的几种组合

解决方法

我遇到过这种情况。我通过部分 bean 的导入和 SpringJUnit4ClassRunner 来解决它: 我会尽量写出主要思想:

@RunWith(SpringJUnit4ClassRunner.class)
@Import({CaffeineCacheManager.class,Catalog.class})
public class CatalogTest {

@MockBean
private Db db;

@Autowired
private CaffeineCacheManager cache;

@Autowired
private Catalog catalog;

@Test
void cacheTest(){
   when(db.someDbMethod()).thenReturn(....);

   catalog.getItems();
   catalog.getItems();

   verify(db,times(1)).someDbMethod();

   assertTrue(cache.get(SOME_KEY).isPresent());//if you want to check that cache contains your entity
}

}

您将拥有真正的缓存 bean,并有机会检查调用模拟 Db 的次数,并且您还可以在测试中获取缓存密钥。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...