blob: 1d2374d0e43cb4b25c4e64a201ed318a82901d8f [file] [log] [blame]
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() {
long userId = 1L;
String token = jwtUtil.generateToken(userId);
assertNotNull(token);
}
@Test
void testValidateTokenAndGetUserId() {
long userId = 1L;
String token = jwtUtil.generateToken(userId);
long extractedUserId = jwtUtil.validateTokenAndGetUserId(token);
assertEquals(userId, extractedUserId);
}
@Test
void testValidateTokenAndGetUsername_InvalidToken() {
String invalidToken = "invalid.token.here";
Exception exception = assertThrows(RuntimeException.class, () ->
jwtUtil.validateTokenAndGetUserId(invalidToken)
);
assertTrue(exception.getMessage().contains("Token无效或过期"));
}
}