From 1f99db9523456c4d736e2b5d1a8c3308c528e17a Mon Sep 17 00:00:00 2001 From: heshunme Date: Mon, 1 Jul 2024 16:46:18 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AF=B9JwtUtil=E7=9A=84?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95=EF=BC=8C=E7=A1=AE=E4=BF=9D?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=8F=AF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../org/cmh/backend/Utils/JwtUtilTest.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/test/java/org/cmh/backend/Utils/JwtUtilTest.java 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); + } +} +