背景
目前项目写单元测试,如果接口中使用到如下代码,是无法获取到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);
}
本文探讨了如何在单元测试中处理接口依赖的token获取问题,通过在测试前设置SecurityContextHolder和MockHttpServletRequest头信息,模拟真实的请求环境。解决方案包括自定义UserDetailsService和使用TestingAuthenticationToken。
986

被折叠的 条评论
为什么被折叠?



