feat: 完善JwtUtil测试类

This commit is contained in:
yulinling 2025-06-24 21:26:17 +08:00
parent 0f6bc1e931
commit 020e319f78
2 changed files with 53 additions and 83 deletions

View File

@ -103,11 +103,6 @@ public class JwtUtil {
// 5. 将token存入redis // 5. 将token存入redis
String redisKey = Const.REDIS_JWT_KEY_PREFIX + username + ":" + userId.toString(); String redisKey = Const.REDIS_JWT_KEY_PREFIX + username + ":" + userId.toString();
try { try {
String isPong = null;
if (stringRedisTemplate.getConnectionFactory() != null) {
isPong = stringRedisTemplate.getConnectionFactory().getConnection().ping();
}
System.out.println("Redis Ping: " + isPong);
stringRedisTemplate.opsForValue().set(redisKey, token, ttl, TimeUnit.SECONDS); stringRedisTemplate.opsForValue().set(redisKey, token, ttl, TimeUnit.SECONDS);
} catch (RedisException e) { } catch (RedisException e) {
log.error("Redis 写入失败: {}", redisKey, e); log.error("Redis 写入失败: {}", redisKey, e);
@ -134,12 +129,9 @@ public class JwtUtil {
String username = claims.getSubject(); String username = claims.getSubject();
Integer userId = (Integer) claims.get("userId"); Integer userId = (Integer) claims.get("userId");
// 2. 获取RedisKey // 2. 获取RedisKey
String redisKey = Const.REDIS_JWT_KEY_PREFIX + username + ":" + userId.toString(); String redisKey = Const.REDIS_JWT_KEY_PREFIX + username + ":" + userId.toString();
System.out.println("Redis Value: " + stringRedisTemplate.opsForValue().get(redisKey));
// 3. 校验Token是否存在 // 3. 校验Token是否存在
Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.SECONDS); Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.SECONDS);
if (expire <= 0) { if (expire <= 0) {
@ -165,7 +157,14 @@ public class JwtUtil {
public Long getUserIdByToken(String token) { public Long getUserIdByToken(String token) {
Claims claims = parseToken(token); Claims claims = parseToken(token);
return (Long) claims.get("userId"); Object userIdObj = claims.get("userId");
if (userIdObj instanceof Long) {
return (Long) userIdObj;
} else if (userIdObj instanceof Integer) {
return ((Integer) userIdObj).longValue();
} else {
throw new IllegalArgumentException("Invalid userId type");
}
} }
public String getUsernameByToken(String token) { public String getUsernameByToken(String token) {
@ -199,7 +198,7 @@ public class JwtUtil {
} }
/** /**
* 设置Token国企 * 设置Token过期
* *
* @param request 请求 * @param request 请求
*/ */

View File

@ -10,20 +10,18 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
@ -36,7 +34,6 @@ import static org.mockito.Mockito.when;
*/ */
@Slf4j @Slf4j
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
@SpringBootTest
class JwtUtilTest { class JwtUtilTest {
@Mock @Mock
private StringRedisTemplate stringRedisTemplate; private StringRedisTemplate stringRedisTemplate;
@ -44,12 +41,27 @@ class JwtUtilTest {
@Mock @Mock
private ValueOperations<String, String> valueOps; private ValueOperations<String, String> valueOps;
@Autowired @InjectMocks
private JwtUtil jwtUtil; private JwtUtil jwtUtil;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
// when(stringRedisTemplate.opsForValue()).thenReturn(valueOps); when(stringRedisTemplate.opsForValue()).thenReturn(valueOps);
}
@Test
public void testGenerateToken() {
// 模拟 UserPrincipal
User user = new User();
user.setId(100L);
user.setUsername("admin");
user.setPassword("admin");
UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of());
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null);
// 生成 token
String token = jwtUtil.generateToken(authentication, false);
assertNotNull(token);
assertTrue(token.startsWith("ey"));
} }
@Test @Test
@ -60,89 +72,48 @@ class JwtUtilTest {
user.setPassword("admin"); user.setPassword("admin");
UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of()); UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of());
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null);
when(stringRedisTemplate.getExpire(anyString(), eq(TimeUnit.SECONDS))).thenReturn(60L);
String token = jwtUtil.generateToken(authentication, false); String token = jwtUtil.generateToken(authentication, false);
assertNotNull(token); assertNotNull(token);
log.info("Generated Token: {}", token); when(valueOps.get(anyString())).thenReturn(token);
Claims claims = jwtUtil.parseToken(token); Claims claims = jwtUtil.parseToken(token);
log.info("Parsed Claims: {}", claims);
assertEquals("admin", claims.getSubject()); assertEquals("admin", claims.getSubject());
} }
@Test @Test
void testGenerateTokenAndValidateToken() { void testGenerateTokenAndValidateToken() {
User user = new User();
Authentication authentication = new UsernamePasswordAuthenticationToken( user.setId(100L);
new MockUserPrincipal(100L, "admin", List.of("ADMIN")), user.setUsername("admin");
null, user.setPassword("admin");
List.of(new SimpleGrantedAuthority("ROLE_ADMIN")) UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of());
); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null);
String token = jwtUtil.generateToken(authentication, false); String token = jwtUtil.generateToken(authentication, false);
System.out.println(token);
assertNotNull(token); assertNotNull(token);
assertTrue(jwtUtil.validateToken(token)); assertTrue(jwtUtil.validateToken(token));
} }
// @Test
// void testValidateToken() {
// UserDetails user = User.withUsername("test")
// .password("test")
// .roles("USER")
// .build();
// Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
// String token = jwtUtil.generateToken(authentication, false);
// assertTrue(jwtUtil.validateToken(token));
// }
@Test @Test
void testValidateToken2() { void testGetUserIdByTokenAndGetUsernameByToken() {
String invalidToken = "this.is.not.valid.jwt"; User user = new User();
assertFalse(jwtUtil.validateToken(invalidToken)); user.setId(100L);
} user.setUsername("admin");
user.setPassword("admin");
@Test UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of());
void testGenerateTokenFromAuthentication() { Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null);
UsernamePasswordAuthenticationToken authentication = // 生成 token
new UsernamePasswordAuthenticationToken( when(stringRedisTemplate.getExpire(anyString(), eq(TimeUnit.SECONDS))).thenReturn(60L);
new MockUserPrincipal(100L, "admin", List.of("ADMIN")),
null,
List.of(new SimpleGrantedAuthority("ROLE_ADMIN"))
);
String token = jwtUtil.generateToken(authentication, false); String token = jwtUtil.generateToken(authentication, false);
assertNotNull(token); assertNotNull(token);
when(valueOps.get(anyString())).thenReturn(token);
Claims claims = jwtUtil.parseToken(token); Long userId = jwtUtil.getUserIdByToken(token);
assertEquals("admin", claims.getSubject()); String username = jwtUtil.getUsernameByToken(token);
} assertEquals(100L, userId);
assertEquals("admin", username);
// Mock UserPrincipal 用于测试
static class MockUserPrincipal extends asia.yulinling.workflow.model.vo.user.UserPrincipal {
private final Long id;
private final String username;
private final List<String> roles;
public MockUserPrincipal(Long id, String username, List<String> roles) {
super(); // 假设父类有默认构造函数
this.id = id;
this.username = username;
this.roles = roles;
}
@Override
public Long getId() {
return id;
}
@Override
public String getUsername() {
return username;
}
@Override
public List<String> getRoles() {
return roles;
}
} }
} }