JwtUtilsTest.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package net.chenlin.dp.common.utils;
  2. import net.chenlin.dp.common.support.properties.JwtProperties;
  3. import org.mockito.InjectMocks;
  4. import org.mockito.Mock;
  5. import org.mockito.Mockito;
  6. import org.mockito.MockitoAnnotations;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.testng.Assert;
  10. import org.testng.annotations.BeforeTest;
  11. import org.testng.annotations.Test;
  12. /**
  13. * JwtUtilsTest
  14. * @author zhouchenglin[yczclcn@163.com]
  15. */
  16. public class JwtUtilsTest {
  17. private static final Logger log = LoggerFactory.getLogger(JwtUtilsTest.class);
  18. @InjectMocks
  19. JwtUtils jwtUtils = new JwtUtils();
  20. @Mock
  21. private JwtProperties jwtProperties;
  22. @BeforeTest
  23. public void init() {
  24. MockitoAnnotations.initMocks(this);
  25. Mockito.when(jwtProperties.getSecret()).thenReturn("dp");
  26. Mockito.when(jwtProperties.getExpiration()).thenReturn(604800L);
  27. Mockito.when(jwtProperties.getMd5Key()).thenReturn("randomKey");
  28. }
  29. @Test
  30. public void test() {
  31. String username = "admin", userId = "111", randomKey = TokenUtils.generateValue();
  32. String token = jwtUtils.generateToken(username, userId, randomKey);
  33. log.info("用户名:{},生成token:{}", username, token);
  34. // 用户名
  35. String jwtSubject = jwtUtils.getUsername(token);
  36. Assert.assertEquals(jwtSubject, username);
  37. // 用户id
  38. String jwtUserId = jwtUtils.getUserId(token);
  39. Assert.assertEquals(jwtUserId, userId);
  40. // 混淆密钥
  41. String jwtRandomKey = jwtUtils.getMd5Key(token);
  42. Assert.assertEquals(jwtRandomKey, randomKey);
  43. }
  44. }