SecurityContextLogoutHandler测试问题

cidc1ykv  于 2023-04-21  发布在  Spring
关注(0)|答案(1)|浏览(161)

有没有什么方法可以用JUnit和Mockito来测试它?
下面是我想测试的一个方法

@RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logoutPage(HttpServletRequest request, HttpServletResponse response)
    {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null)
        {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return "redirect:/login?logout";
    }

注销测试

@Test
    public void testLogoutPage() throws Exception
    {
        MockHttpServletRequestBuilder requestBuilder = get("/logout");
        MockMvcBuilders.standaloneSetup(this.loginController)
                .build()
                .perform(requestBuilder)
                .andExpect(status().isFound())
                .andExpect(MockMvcResultMatchers.model().size(0))
                .andExpect(view().name("redirect:/login?logout"))
                .andExpect(MockMvcResultMatchers.redirectedUrl("/login?logout"));
    }

测试涵盖了一切,除了。

new SecurityContextLogoutHandler().logout(request, response, auth);

我尝试了一些Assert,但总是得到NullPointerException。

neskvpey

neskvpey1#

您可以通过向expect链添加unauthenticated()来测试您是否已注销。

  • 库:JUnit 5和Sping Boot 2.7.1*
@Test
public void testLogoutPage() throws Exception
{
    MockHttpServletRequestBuilder requestBuilder = get("/logout");
    MockMvcBuilders.standaloneSetup(this.loginController)
            .build()
            .perform(requestBuilder)
            .andExpect(unauthenticated()) // Added
            .andExpect(status().isFound())
            .andExpect(MockMvcResultMatchers.model().size(0))
            .andExpect(view().name("redirect:/login?logout"))
            .andExpect(MockMvcResultMatchers.redirectedUrl("/login?logout"));
}

相关问题