Search code examples
javaspringredisspring-dataspring-cache

How to wait for Redis cache to cache the information


I am using spring-data-redis and trying to have a junit with which, I can test my Caching logic. The test case sporadically works. I guess if the caching logic completes before the invocation of the second method call then it works else it fails. If some has faced a similar issue, I will like to understand how they made it work. As of now, I am using thread.sleep() but looking for an alternative.

  @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());
}

Solution

  • The actual issue was not with the Thread wait time. For Redis cache to work a separate thread need to be spanned. For my service test, I tested it via a separated test case.

     @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());
     }