[FIXED] How to avoid 302 response on https spring security unit test?

Issue

I’ve got java Spring Security app (built with jhipster) and I’m trying to add some unit tests that test logic based on the current authenticated user.

To do that i’ve configured my MockMvc object to use a web application context and spring security as so:

@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’ve also configured the app to require HTTPS, and whenever I run this unit test I get a 302 redirect response since it appears to be trying to send an HTTP request instead of HTTPS.

The way I’ve enforced HTTPS is with the following line in SecurityConfiguration.configure(HttpSecurity http):

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

So, my question is how can I get my unit test to run correctly? Probably either by sending a mock HTTPS request, or by disabling HTTPS in the case of running a unit test?

Solution

Using Springs MockMvc stuff you can also specify that you want to send a mock HTTPS request using the secure(true) method as follows:

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

Answered By – rhinds

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published