LogoutSuccessHandler单元案例不起作用

时间:2017-08-03 02:09:17

标签: java spring unit-testing spring-boot spring-security

LogoutSuccessHandler的集成测试无效。

我在Spring安全应用程序中将LogoutSuccessHandler实现为CustomLogOutHandler。在运行应用程序时,一切正常,这个自定义注销处理程序在我从应用程序注销时被调用。

但是在为它编写单元测试用例时,我无法调用此CustomLogOutHandler,并且流程将转到应用程序中编写的其他过滤器。

代码段如下:

public class CustomLogOutHandler implements LogoutSuccessHandler {
  private final static Logger logger = Logger.getLogger(CustomLogOutHandler.class);
  @Autowired
  private SessionContextRepository redisContextRepository;

 @Autowired
  private SessionService sessionService;

  @Value("X-Auth-Token")
  private String tokenHeader;

  @Override
  public void onLogoutSuccess(HttpServletRequest httpServletRequest, 
    HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
    if (httpServletRequest != null) {
      .....
    }

配置如下:

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.csrf().disable();
    http.authorizeRequests()
            .antMatchers(
                    "/",
                    "/errors/portal/*",
                    "/error**"
            ) //internal login
            .permitAll().anyRequest().authenticated()
            .and().logout().logoutSuccessHandler(getCustomLogOutHandler())
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));

我的测试类看起来像:

RedisSessionContext context = Mockito.mock(RedisSessionContext.class);
Mockito.doNothing().when(rediscontext).deleteSessionContext(Mockito.anyString());

Mockito.when(rediscontext.getSessionContext(Mockito.anyString())).thenReturn(context);
    RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/logout").header("userName", "00001011181")
            .accept(MediaType.APPLICATION_JSON);
    MvcResult result = mockMvc.perform(requestBuilder)
            .andReturn();
    Assert.assertNotNull("Token is null", result.getResponse().getHeader("authToken"));

非常感谢任何帮助。

0 个答案:

没有答案