背景
目前项目写单元测试,如果接口中使用到如下代码,是无法获取到token的
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String bearerAndtoken = request.getHeader("AUTHORIZATION")
解决方案
在单元测试中加入如下代码。 (注: token需自己通过post公司的获取token地址)
@Before
public void beforeMethod() {
// xxx表示 implements UserDetailsService 的类
UserDetails user= xxxxx.loadUserByUsername("账号");
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(user, ""));
//设置token
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return;
}
MockHttpServletRequest request = (MockHttpServletRequest) attributes.getRequest();
request.addHeader("AUTHORIZATION", "Bearer " + token);
}