相关疑难解决方法(0)

如何测试Spring对Spring Data存储库的声明性缓存支持?

我开发了一个MemberRepository扩展的Spring Data存储库接口org.springframework.data.jpa.repository.JpaRepository.MemberRepository有一个方法:

@Cacheable(CacheConfiguration.DATABASE_CACHE_NAME)
Member findByEmail(String email);
Run Code Online (Sandbox Code Playgroud)

结果由Spring缓存抽象缓存(由a支持ConcurrentMapCache).

我的问题是,我想要写一个集成测试(针对HSQLDB)断言结果被从数据库第一次检索,并从缓存中的第二次.

我最初想过嘲笑jpa基础设施(实体经理等),并以某种方式断言实体经理第二次没有被调用但看起来太难/笨重(参见/sf/answers/1640972021/).

那么有人可以提供有关如何测试带有注释的Spring Data Repository方法的缓存行为的建议@Cacheable吗?

testing spring spring-data spring-data-jpa spring-cache

33
推荐指数
1
解决办法
2万
查看次数

通过SpringCache缓存嵌套的可缓存操作

我被赋予了将SpringCache用于我们的一项服务以减少数据库查找次数的任务.在测试实现时,我注意到一些可缓存的操作是通过log-statements多次调用的.调查显示,如果在可缓存方法中调用可缓存操作,则根本不缓存嵌套操作.因此,稍后调用嵌套操作会导致进一步查找.

下面列出了一个描述问题的简单单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringCacheTest.Config.class} )
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class SpringCacheTest {

  private final static String CACHE_NAME = "testCache";
  private final static Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
  private final static AtomicInteger methodInvocations = new AtomicInteger(0);

  public interface ICacheableService {

    String methodA(int length);
    String methodB(String name);
  }

  @Resource
  private ICacheableService cache;

  @Test
  public void testNestedCaching() {

    String name = "test";
    cache.methodB(name);
    assertThat(methodInvocations.get(), is(equalTo(2)));

    cache.methodA(name.length());
    // should only be 2 as methodA for this length was already invoked before
    assertThat(methodInvocations.get(), is(equalTo(3))); …
Run Code Online (Sandbox Code Playgroud)

java spring caching

3
推荐指数
1
解决办法
1125
查看次数