diff --git a/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java b/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java new file mode 100644 index 0000000..78dcdb8 --- /dev/null +++ b/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java @@ -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); + } +} +