添加对JwtUtil的单元测试,确保功能可用

This commit is contained in:
高子兴 2024-07-01 16:46:18 +08:00
parent cbf066b113
commit 1f99db9523

View File

@ -0,0 +1,47 @@
package org.cmh.backend.Utils;
import io.jsonwebtoken.Claims;
import org.junit.Assert;
import org.junit.Test;
import java.util.Date;
public class JwtUtilTest {
@Test
public void testGenerateToken() throws InterruptedException {
String username = "testUser";
String token = JwtUtil.generateToken(username);
Thread.sleep(100);
// Validate token is not empty
Assert.assertNotNull("Token should not be null", token);
Assert.assertFalse("Token should not be empty", token.isEmpty());
// Parse the token to check claims
Claims claims = JwtUtil.extractClaims(token);
// System.out.println(claims.getIssuedAt().toString());
// Validate claims
Assert.assertTrue("Token shoud be valid", JwtUtil.isTokenValid(token, username));
Assert.assertEquals("Username in claims should match", username, claims.getSubject());
Assert.assertTrue("Token should be issued in the past", new Date().after(claims.getIssuedAt()));
Assert.assertTrue("Token expiration should be in the future", new Date().before(claims.getExpiration()));
}
@Test
public void testTokenExpiration() {
String username = "testUser";
String token = JwtUtil.generateToken(username);
Claims claims = JwtUtil.extractClaims(token);
long expirationTime = claims.getExpiration().getTime();
long currentTime = new Date().getTime();
// Validate token expires within 10 hours
Assert.assertTrue("Token should expire within 10 hours", expirationTime - currentTime <= 1000 * 60 * 60 * 10);
}
}