我正在使用 Spring Boot 并设置了 Spring Security 以使用 token 授权。我的测试设置如下:
@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("/")
发送 header “X-AUTH: SOMETOKEN”我怎么做?
最佳答案
.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]}
关于Spring MockMvc 和 @AutoConfigureMockMvc() 在请求中设置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48292127/