Spring Security+Mock MVC测试断言错误:重定向URL含主机名问题
Spring Security测试重定向URL差异问题
失败的测试及错误
我编写了如下测试:
@Test @WithAnonymousUser void givenNoAuthentication_whenEnteringMainPage_thenRedirectToLoginPage() throws Exception { mockMvc.perform(get("/")).andExpect(redirectedUrl("/login")); }
执行后抛出断言错误:
java.lang.AssertionError: Redirected URL expected:</login> but was:<http://localhost/login> Expected :/login Actual :http://localhost/login
正常运行的对比测试
另有一个类似测试可正常运行:
@Test @WithMockUser void givenAuthentication_whenEnteringLoginPage_thenRedirectToMainPage() throws Exception { mockMvc.perform(get("/login")).andExpect(redirectedUrl("/")); }
我的Spring Security配置
配置类代码如下:
@Configuration public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .authorizeHttpRequests(authorize -> authorize .requestMatchers("/css/**").permitAll() .requestMatchers("/js/**").permitAll() .requestMatchers("/login").permitAll() .requestMatchers("/register").permitAll() .requestMatchers("/user/register").permitAll() .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/login") .defaultSuccessUrl("/", true) ) .logout(logout -> logout .logoutUrl("/logout") .logoutSuccessUrl("/login") ) .build(); } @Bean public static PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
临时修复方案
我通过endsWith方法临时修复了测试:
MvcResult result = mockMvc.perform(get("/")).andReturn(); assertThat(result.getResponse().getRedirectedUrl()).endsWith("/login");
疑问
我不理解为什么第一个测试的重定向URL包含主机名http://localhost,而第二个测试的重定向URL只有路径/。
内容的提问来源于stack exchange,提问作者Nerfi
相关产品推荐
相关产品推荐

