【发布时间】:2019-08-16 01:36:29
【问题描述】:
我正在使用 spring-data-redis 并尝试使用 junit 来测试我的缓存逻辑。测试用例偶尔会起作用。我猜如果缓存逻辑在调用第二个方法调用之前完成,那么它会起作用,否则它会失败。如果有些人遇到过类似的问题,我想了解他们是如何做到的。截至目前,我正在使用 thread.sleep() 但正在寻找替代方案。
@Test
public void getUserById() {
User user = new User("name", "1234");
when(userRepository.findbyId("1234")).thenReturn(Optional.ofNullable(user));
// first method call
User user1 = userService.findbyId("1234");
assertThat(user.getName()).isEqualTo(user1.getName());
assertThat(user.getId).isEqualTo(user1.getId());
// sleeping the thread so to provide caching aspect sufficient time
// to cache the information
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// second method call, expecting cache to work.
userCache = userService.findbyId("1234");
verify(userRepository, never()).findbyId("1234");
assertThat(user.getName()).isEqualTo(userCache.getName());
assertThat(user.getId).isEqualTo(userCache.getId());
}
【问题讨论】:
标签: java spring redis spring-data spring-cache