Search code examples
junit5

Mocked save returns null. Cannot find the difference


I'm using Junit 5.

This is my test:

@Test
void testCanCreateRefreshToken() {

    var usersEntity = UsersEntity.builder().id(7L).username("username").password("thisIsAPassword").build();

    var refreshTokensEntity = validRefreshTokensEntity(null, "this.is.token", usersEntity, Instant.now());

    var savedRefreshTokensEntity = validRefreshTokensEntity(1L, "this.is.token", usersEntity, Instant.now());

    when(usersRepository.findById(7L)).thenReturn(Optional.of(usersEntity));
         
     when(refreshTokensRepository.save(refreshTokensEntity)).thenReturn(savedRefreshTokensEntity);

    assertEquals(savedRefreshTokensEntity, refreshTokensService.createRefreshToken(7L));

}

And this is the method:

public RefreshTokensEntity createRefreshToken(Long userId) {
        RefreshTokensEntity refreshTokensEntity = new RefreshTokensEntity();
        refreshTokensEntity.setUsersEntity(usersRepository.findById(userId).get());
        refreshTokensEntity.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
        refreshTokensEntity.setToken(UUID.randomUUID().toString());
        RefreshTokensEntity saved = refreshTokensRepository.save(refreshTokensEntity);
        return saved;
    }

System.out.println of refreshTokenEntity in real method:

RefreshTokensEntity(id=null, token=85c448be-11d2-43c6-8cc4-41f3a68fe4cb, usersEntity=UsersEntity(id=7, username=username, password=thisIsAPassword), expiryDate=2022-02-28T20:13:38.056212944Z)

System.out.println of refreshTokenEntity in test:

RefreshTokensEntity(id=null, token=this.is.token, usersEntity=UsersEntity(id=7, username=username, password=thisIsAPassword), expiryDate=2022-02-28T20:13:26.332206931Z)

Of course, if I pass any() I can validate test.

Is it possible the issues are the token and the expiryDate? So, I need to place them in a external class and mocked them...


Solution

  • I leave my own answer for somebody that can have same issue.

    Yes, the issue was the variable values of token and ExpiryDate.

    So, I create two different classes to manipulate them and use them as mocked.

    So I can have same value in every test.

    E.g.:

    String refreshToken = "this-is-a-refreh-token";
    when(jwtUtils.generateRefreshToken()).thenReturn(refreshToken);