blob: 860acec0a2cfb07c4ddae7935bbb5caaeaf49f64 [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() {
28 String username = "testUser";
29 String token = jwtUtil.generateToken(username);
30 assertNotNull(token);
31 }
32
33 @Test
34 void testValidateTokenAndGetUsername() {
35 String username = "testUser";
36 String token = jwtUtil.generateToken(username);
37 String extractedUsername = jwtUtil.validateTokenAndGetUsername(token);
38 assertEquals(username, extractedUsername);
39 }
40
41 @Test
42 void testValidateTokenAndGetUsername_InvalidToken() {
43 String invalidToken = "invalid.token.here";
44 Exception exception = assertThrows(RuntimeException.class, () ->
45 jwtUtil.validateTokenAndGetUsername(invalidToken)
46 );
47 assertTrue(exception.getMessage().contains("Token无效或过期"));
48 }
49}