| package com.example.g8backend.util; |
| |
| import org.junit.jupiter.api.BeforeEach; |
| import org.junit.jupiter.api.Test; |
| import org.mockito.InjectMocks; |
| import org.mockito.MockitoAnnotations; |
| import static org.junit.jupiter.api.Assertions.*; |
| import io.jsonwebtoken.security.Keys; |
| import javax.crypto.SecretKey; |
| import java.security.SecureRandom; |
| |
| class JwtUtilTest { |
| |
| @InjectMocks |
| private JwtUtil jwtUtil; |
| |
| @BeforeEach |
| void setUp() { |
| MockitoAnnotations.openMocks(this); |
| byte[] keyBytes = new byte[32]; |
| new SecureRandom().nextBytes(keyBytes); |
| SecretKey secretKey = Keys.hmacShaKeyFor(keyBytes); |
| jwtUtil = new JwtUtil(secretKey); |
| } |
| |
| @Test |
| void testGenerateToken() { |
| String username = "testUser"; |
| String token = jwtUtil.generateToken(username); |
| assertNotNull(token); |
| } |
| |
| @Test |
| void testValidateTokenAndGetUsername() { |
| String username = "testUser"; |
| String token = jwtUtil.generateToken(username); |
| String extractedUsername = jwtUtil.validateTokenAndGetUsername(token); |
| assertEquals(username, extractedUsername); |
| } |
| |
| @Test |
| void testValidateTokenAndGetUsername_InvalidToken() { |
| String invalidToken = "invalid.token.here"; |
| Exception exception = assertThrows(RuntimeException.class, () -> |
| jwtUtil.validateTokenAndGetUsername(invalidToken) |
| ); |
| assertTrue(exception.getMessage().contains("Token无效或过期")); |
| } |
| } |