Spring Security + Mock MVC Testing - ошибка утверждения, URL-адрес перенаправления «http://localhost/login» вместо «/logJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Spring Security + Mock MVC Testing - ошибка утверждения, URL-адрес перенаправления «http://localhost/login» вместо «/log

Сообщение Anonymous »


I have such a test

@Test @WithAnonymousUser void givenNoAuthentication_whenEnteringMainPage_thenRedirectToLoginPage() throws Exception { mockMvc.perform(get("/")).andExpect(redirectedUrl("/login")); } And I got assertion error like this:

java.lang.AssertionError: Redirected URL expected: but was: Expected :/login Actual :http://localhost/login What is more, I have another test similar to this one which tests if logged in user gets redirected to main page ("/") after accessing /login and this test is working fine

@Test @WithMockUser void givenAuthentication_whenEnteringLoginPage_thenRedirectToMainPage() throws Exception { mockMvc.perform(get("/login")).andExpect(redirectedUrl("/")); } Here is how my spring security config looks like

@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(); } } How can I fix my first test, and why it doesnt't work when second test which is almost the same is working fine?

EDIT: I managed to fix this by using .endsWith("/login") like so

MvcResult result = mockMvc.perform(get("/")).andReturn(); assertThat(result.getResponse().getRedirectedUrl()).endsWith("/login"); But I still don't understand why in this test redirect url contains hostname, and it other it doesn't


Источник: https://stackoverflow.com/questions/781 ... http-local
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»