添加对JwtUtil的单元测试,确保功能可用
This commit is contained in:
parent
cbf066b113
commit
1f99db9523
47
src/test/java/org/cmh/backend/Utils/JwtUtilTest.java
Normal file
47
src/test/java/org/cmh/backend/Utils/JwtUtilTest.java
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Reference in New Issue
Block a user