package com.xly.erp.common.security; import com.xly.erp.common.exception.BizException; import com.xly.erp.common.response.ErrorCode; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest @ActiveProfiles("test") class JwtUtilTest { @Autowired private JwtUtil jwtUtil; private Map sampleClaims() { Map claims = new HashMap<>(); claims.put("sub", "42"); claims.put("username", "alice"); claims.put("userType", "NORMAL"); claims.put("companyCode", "HQ"); claims.put("language", "zh-CN"); return claims; } @Test void issuedToken_canBeParsedBackToClaims() { String token = jwtUtil.issue(sampleClaims(), 7200); assertNotNull(token); assertFalse(token.isEmpty()); Map parsed = jwtUtil.parse(token); assertEquals("42", parsed.get("sub")); assertEquals("alice", parsed.get("username")); assertEquals("NORMAL", parsed.get("userType")); assertEquals("HQ", parsed.get("companyCode")); assertEquals("zh-CN", parsed.get("language")); assertNotNull(parsed.get("jti")); assertNotNull(parsed.get("iat")); assertNotNull(parsed.get("exp")); long iat = ((Number) parsed.get("iat")).longValue(); long exp = ((Number) parsed.get("exp")).longValue(); assertEquals(7200L, exp - iat, "exp - iat 必须严格等于 ttlSec(spec § 验收 § 2)"); } @Test void tamperedToken_throwsBizException() { String token = jwtUtil.issue(sampleClaims(), 7200); String tampered = token.substring(0, token.length() - 4) + "XXXX"; BizException e = assertThrows(BizException.class, () -> jwtUtil.parse(tampered)); assertEquals(ErrorCode.BAD_CREDENTIALS, e.getCode()); } @Test void expiredToken_throwsBizException() { String token = jwtUtil.issue(sampleClaims(), 0L); try { Thread.sleep(1100); } catch (InterruptedException ignored) {} BizException e = assertThrows(BizException.class, () -> jwtUtil.parse(token)); assertEquals(ErrorCode.BAD_CREDENTIALS, e.getCode()); } }