我应该如何测试@authentificationprincipal?

问题描述 投票:0回答:1

我得到了@PostMapping("/login") 公共字符串 postLogin(@AuthenticationPrincipal CustomUserDetails userDetails) { authService.auth(userDetails.getId()); 返回“重定向:/main”; } 和测试方法:@Test void postLogin_success() 抛出异常 { UserDTO userDTO = createUserDTO(1, "用户", "[电子邮件受保护]", "密码");

    when(authService.auth(anyInt())).thenReturn(userDTO);

    mockMvc.perform(post("/login")
                    .with(csrf())
                    .principal(authenticationToken)
                    .characterEncoding("UTF-8")
                    .param("email", "[email protected]")
                    .param("password", "password"))
            .andDo(print())
            .andExpect(status().is3xxRedirection())
            .andExpect(redirectedUrl("/main"));
} but it shows an error: java.lang.AssertionError: Redirected URL expected:</main> but was:</login?error>

预期:/main 实际:/登录?错误

java spring-boot spring-mvc spring-security
1个回答
0
投票

如果Spring Security的身份验证失败,则不会注入userDetails,Spring Security将重定向到失败的URL(/login?error)。也许您的测试设置无法正确验证?如果您到达那里,请尝试登录您的控制器(如果您进行了身份验证)。然后检查/调试您的 authService (authService.auth(userDetails.getId())) 的功能。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.