blob: 1d2374d0e43cb4b25c4e64a201ed318a82901d8f [file] [log] [blame]
wuchimedesa573ea12025-04-03 17:46:50 +08001package com.example.g8backend.util;
2
3import org.junit.jupiter.api.BeforeEach;
4import org.junit.jupiter.api.Test;
5import org.mockito.InjectMocks;
6import org.mockito.MockitoAnnotations;
7import static org.junit.jupiter.api.Assertions.*;
8import io.jsonwebtoken.security.Keys;
9import javax.crypto.SecretKey;
10import java.security.SecureRandom;
11
12class 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() {
wuchimedes223bfab2025-04-04 17:16:05 +080028 long userId = 1L;
29 String token = jwtUtil.generateToken(userId);
wuchimedesa573ea12025-04-03 17:46:50 +080030 assertNotNull(token);
31 }
32
33 @Test
wuchimedes223bfab2025-04-04 17:16:05 +080034 void testValidateTokenAndGetUserId() {
35 long userId = 1L;
36 String token = jwtUtil.generateToken(userId);
37 long extractedUserId = jwtUtil.validateTokenAndGetUserId(token);
38 assertEquals(userId, extractedUserId);
wuchimedesa573ea12025-04-03 17:46:50 +080039 }
40
41 @Test
42 void testValidateTokenAndGetUsername_InvalidToken() {
43 String invalidToken = "invalid.token.here";
44 Exception exception = assertThrows(RuntimeException.class, () ->
wuchimedes223bfab2025-04-04 17:16:05 +080045 jwtUtil.validateTokenAndGetUserId(invalidToken)
wuchimedesa573ea12025-04-03 17:46:50 +080046 );
47 assertTrue(exception.getMessage().contains("Token无效或过期"));
48 }
49}