@Test
public void getUsers_Success() throws Exception {
when(userRepository.findAll()).thenReturn(userList.getUsers());
String token = TokenAuthenticationService.createToken("me@me.com");
assertNotNull(token);
RequestBuilder request = MockMvcRequestBuilders
.get("/api/v1/users")
.header("Authorization", "Bearer "+ token);
MvcResult result = mockMvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().json(usersJson))
.andReturn();
result.getResponse().getContentAsString();
}
这是 token 生成
public static String createToken(String username) {
String jwt = Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
return jwt;
}
当我运行此测试时,响应始终为空。然后 json 解析失败,因为响应为空。
最佳答案
方法 signWith(SignatureAlgorithm.HS512, SECRET)
已弃用,并将在未来版本中删除。你应该使用:
signWith(SECRET, SignatureAlgorithm.HS512)
我认为 SECRET 是一个 String 对象 => 你需要根据你的 secret 生成 secret key :
signWith(Keys.hmacShaKeyFor(SECRET.getBytes()), SignatureAlgorithm.HS512)
关于java - 在 JUnit 测试中给定 JWT token 时,MockMVC 不返回任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58545347/