Py学习  »  Redis

如何等待redis缓存缓存信息

JDev • 4 年前 • 540 次点击  

我正在使用SpringDataRedis并尝试使用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());
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38936
 
540 次点击  
文章 [ 2 ]  |  最新文章 4 年前
JDev
Reply   •   1 楼
JDev    5 年前

实际问题不在线程等待时间内。要使redis缓存工作,需要跨越一个单独的线程。对于我的服务测试,我通过一个单独的测试用例来测试它。

 @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());
 }
 //ensure this test case is executed after getUserById. I used 
 //@FixMethodOrder(MethodSorters.NAME_ASCENDING)
 @Test
 public void getUserById_cache() {
   User user1 = userService.findbyId("1234");
   Mockito.verify(userRepository, never()).findbyId("1234")
   assertThat(user.getName()).isEqualTo(user1.getName());
   assertThat(user.getId).isEqualTo(user1.getId());
 }
mle
Reply   •   2 楼
mle    5 年前

运行时问题,而等待的时间很短,这在分布式系统中非常常见。为了弥补等待测试断言太长时间的需要,有一个叫做 Awaitility .

有了这个,您基本上可以通过多次查询断言来进行更聪明的等待,以一定的间隔,直到达到给定的超时(以及更多)。

关于您的示例,请尝试以下操作:

        Awaitility.await()
                .pollInterval(new Duration(1, TimeUnit.SECONDS))
                .atMost(new Duration(10, TimeUnit.SECONDS))
                .untilAsserted(() -> 
                    User user1 = userService.findbyId("1234");
                    assertThat(user1.getName()).isEqualTo(user.getName());

关于问题的另一部分,在集成测试中,实际上可以对 Redis 或者,如果您有一个容器化的集成测试(例如Docker),您可以对它发出一些第一个请求,或者 wait for a certain condition 在开始测试之前。