Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MockMvc and @AutoConfigureMockMvc() set headers in request

I'm using Spring boot and have Spring Security setup to use token authorization. I have my test is setup like so:

@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
})
@AutoConfigureMockMvc()
@EnableAutoConfiguration(exclude = {
})
public class ApplicationTests {
@Test
        public void shouldReturnRepositoryIndex() throws Exception {

            mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()).andExpect(
                    jsonPath("$._links.people").exists());
        }
}

I need get("/") to send a header "X-AUTH: SOMETOKEN"

How do I do that?

like image 497
mikeb Avatar asked Dec 04 '22 20:12

mikeb


1 Answers

.header("X-AUTH" , "SOMETOKEN") should work.

Here is the modified mockMvc code:

mockMvc.perform(get("/").header("X-AUTH" , "SOMETOKEN")).andDo(print()).andExpect(status().isOk()).andExpect(
            jsonPath("$._links.people").exists());

The output is:

MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /
   Parameters = {}
      Headers = {X-AUTH=[SOMETOKEN]}
like image 134
Alex M981 Avatar answered May 23 '23 13:05

Alex M981