我目前正在使用JWT编写Spring Boot应用程序。在使用不同的日期测试负责创建令牌的功能时,我遇到了一个问题。好吧,我得到了NullPointer而不是令牌。我就是这样测试的:
@Test
public void testGenerateTokenFromDifferentDates() {
when(clockMock.now())
.thenReturn(DateUtil.yesterday())
.thenReturn(DateUtil.now());
String token = createToken();
String tokenLater = createToken();
assertThat(token).isNotEqualTo(tokenLater);
}
private String createToken() {
String token = tokenUtil.generateToken(new TestUser(USERNAME));
return token;
}
这是负责创建令牌的类:
@Component
public class TokenUtil implements Serializable {
private static final long serialVersionUID = -3301605591108950415L;
@Value("${jwt.secret}")
private String secret;
private Clock clock = DefaultClock.INSTANCE;
@Value("${jwt.expires.days}")
private Long expiration;
public String getUsernameFromToken(String token) {
return getClaimsFromToken(token, Claims::getSubject);
}
public <T> T getClaimsFromToken(String token, Function<Claims, T> resolverClaims) {
final Claims claims = getAllClaimsFromToken(token);
return resolverClaims.apply(claims);
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJwt(token).getBody();
}
private String doGenerateToken(Map<String, Object> claims, String subject) {
final Date createdDate = clock.now();
final Date expirationDate = calculateExpirationDate(createdDate);
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, this.secret)
.compact();
}
private Date calculateExpirationDate(Date createdDate) {
return new Date(createdDate.getTime() + expiration * 1000);
}
}
我不知道可能是什么原因。调试器也无济于事,因为目前还没有。这是repository。 正如@theonlyrao建议的,这里是堆栈跟踪:
java.lang.NullPointerException
at com.github.springjwt.security.jwt.TokenUtil.calculateExpirationDate(TokenUtil.java:59)
at com.github.springjwt.security.jwt.TokenUtil.doGenerateToken(TokenUtil.java:47)
at com.github.springjwt.security.jwt.TokenUtil.generateToken(TokenUtil.java:38)
at com.github.springjwt.security.jwt.TokenUtilTest.createToken(TokenUtilTest.java:42)
at com.github.springjwt.security.jwt.TokenUtilTest.testGenerateTokenFromDifferentDates(TokenUtilTest.java:35)
答案 0 :(得分:1)
似乎createdDate
或expiration
为空。
我不确定createdDate
的实例化方式,因为我没有使用过该DefaultClock
库。
我认为expiration
的问题在于您没有告诉Spring在哪里可以找到测试中的应用程序属性。除非在代码的其他地方发生这种情况,否则您需要按照https://www.baeldung.com/spring-classpath-file-access中所述指定资源的路径。