如何处理长期在Java的测试?

How deal with testing in Java for long time?

我想测试这个方法:

/**
  * Get the expiry date from a token
  * 
  * @param token
  * @return the expiry date
  */
  public Long getExpiryDateFromJwtToken(String token) {
    return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getExpiration().getTime();
}

这就是测试(是的,测试比方法更长 :)):

    @Test
    void canGetExpiryDateFromJwtToken() {

        // Set the security context
        SecurityContextHolder.setContext(securityContext);
        
        // Mock the time at.. now
        Long currentTimeMillis = System.currentTimeMillis();

        // Mock the methods
        when(timeSource.getCurrentTimeMillis()).thenReturn(currentTimeMillis);
        when(securityContext.getAuthentication()).thenReturn(authentication);
        
        // Create an usersEntitiy
        UsersEntity usersEntity = new UsersEntity(1L, "username", "password");
        // Build the entity to return from getPrincipal
        UserDetailsImpl user = UserDetailsImpl.build(usersEntity);
        when(authentication.getPrincipal()).thenReturn(user);
        
        // Finally, generate a token
        String token = jwtUtils.generateJwtToken(authentication);
        
        // Get the expiry date (our method under test)
        Long expiryDate = jwtUtils.getExpiryDateFromJwtToken(token);
        
        // Finally, assert equals
        assertEquals(currentTimeMillis+86400000, expiryDate);
    }

但是,我有一个小的时钟偏移。

例如:

AssertionFailedError: expected: <1646512977798> but was: <1646512977000>

所以,时间是一样的,只相差798左右

编辑 1

目前,我解决了:

// Finally, assert equals. Accept a small clock shift
Long expectedExpiryDate = currentTimeMillis + Long.parseLong(jwtExpirationMs);
assertEquals(expectedExpiryDate/10000, expiryDate/10000);

有没有更优雅的方法?

一般来说,当您使用时态数据类型时,传递一个 java.time.Clock 是个好主意,这样您就可以设置时间和控制环境。

实施 https://github.com/bezkoder/spring-boot-spring-security-jwt-authentication/blob/master/src/main/java/com/bezkoder/springjwt/security/jwt/JwtUtils.java 中的问题与 new Date() 有关。建议:克隆此实现并制作更好的 generateJwtToken 并接受 Clock 以便您可以控制时间戳。