Spring MockMvc和@AutoConfigureMockMvc()在请求中设置标头

时间:2018-01-17 00:55:30

标签: spring spring-mvc spring-boot

我正在使用Spring启动并使用Spring Security设置来使用令牌授权。我的测试设置如下:

@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());
        }
}

我需要get("/")发送标题“X-AUTH:SOMETOKEN”

我该怎么做?

1 个答案:

答案 0 :(得分:3)

.header("X-AUTH" , "SOMETOKEN")应该有用。

以下是修改后的mockMvc代码:

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

输出结果为:

MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /
   Parameters = {}
      Headers = {X-AUTH=[SOMETOKEN]}