wuchimedes | a573ea1 | 2025-04-03 17:46:50 +0800 | [diff] [blame] | 1 | package com.example.g8backend.util; |
| 2 | |
| 3 | import org.junit.jupiter.api.BeforeEach; |
| 4 | import org.junit.jupiter.api.Test; |
| 5 | import org.mockito.InjectMocks; |
| 6 | import org.mockito.MockitoAnnotations; |
| 7 | import static org.junit.jupiter.api.Assertions.*; |
| 8 | import io.jsonwebtoken.security.Keys; |
| 9 | import javax.crypto.SecretKey; |
| 10 | import java.security.SecureRandom; |
| 11 | |
| 12 | class JwtUtilTest { |
| 13 | |
| 14 | @InjectMocks |
| 15 | private JwtUtil jwtUtil; |
| 16 | |
| 17 | @BeforeEach |
| 18 | void setUp() { |
| 19 | MockitoAnnotations.openMocks(this); |
| 20 | byte[] keyBytes = new byte[32]; |
| 21 | new SecureRandom().nextBytes(keyBytes); |
| 22 | SecretKey secretKey = Keys.hmacShaKeyFor(keyBytes); |
| 23 | jwtUtil = new JwtUtil(secretKey); |
| 24 | } |
| 25 | |
| 26 | @Test |
| 27 | void testGenerateToken() { |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 28 | long userId = 1L; |
| 29 | String token = jwtUtil.generateToken(userId); |
wuchimedes | a573ea1 | 2025-04-03 17:46:50 +0800 | [diff] [blame] | 30 | assertNotNull(token); |
| 31 | } |
| 32 | |
| 33 | @Test |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 34 | void testValidateTokenAndGetUserId() { |
| 35 | long userId = 1L; |
| 36 | String token = jwtUtil.generateToken(userId); |
| 37 | long extractedUserId = jwtUtil.validateTokenAndGetUserId(token); |
| 38 | assertEquals(userId, extractedUserId); |
wuchimedes | a573ea1 | 2025-04-03 17:46:50 +0800 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | @Test |
| 42 | void testValidateTokenAndGetUsername_InvalidToken() { |
| 43 | String invalidToken = "invalid.token.here"; |
| 44 | Exception exception = assertThrows(RuntimeException.class, () -> |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 45 | jwtUtil.validateTokenAndGetUserId(invalidToken) |
wuchimedes | a573ea1 | 2025-04-03 17:46:50 +0800 | [diff] [blame] | 46 | ); |
| 47 | assertTrue(exception.getMessage().contains("Token无效或过期")); |
| 48 | } |
| 49 | } |