How to avoid 302 answer on https spring security unit test?

I have a java Spring security application (built using jhipster) and I am trying to add some unit tests that check the logic based on the current authenticated user.

To do this, I configured my object MockMvcto use the web application context and Spring Security as follows:

@Test
@Transactional
public void getAllContacts() throws Exception {
    restContactMockMvc = MockMvcBuilders
        .webAppContextSetup(context)
        .apply(springSecurity())
        .build();
    restContactMockMvc.perform(get("/api/contacts")).andExpect(status().isOk());
}

The problem is that I also configured the application on HTTPS, and whenever I run this unit test, I get a 302 redirect response as it tries to send an HTTP request instead of HTTPS.

The way I used HTTPS has the following line in SecurityConfiguration.configure(HttpSecurity http):

if (env.acceptsProfiles("!dev"))http.requiresChannel().anyRequest().requiresSecure();

, : unit test ? , mock HTTPS-, HTTPS unit test?

+4
2

Springs MockMvc, , mock HTTPS secure (true) :

restContactMockMvc.perform( get("/api/contacts").secure( true ) ).andExpect( status().isOk() )
+6

, , , . - .

SecurityConfiguration.configure(HttpSecurity http) if https, , Test:

if (env.acceptsProfiles("!dev") && !((StandardEnvironment) env).getPropertySources().contains("integrationTest")) {
        http.requiresChannel().anyRequest().requiresSecure();
}
0

Source: https://habr.com/ru/post/1623838/


All Articles