如何根据测试注释向MockMvc请求添加标头?

时间:2018-01-31 14:14:09

标签: spring-test spring-security-test

作为this question的后续,我想知道如何透明地添加&#34;授权&#34;标题为 <button ion-button (ionFocusout)="checkFocus()">Click Me</button> ,仅当测试中存在给定注释时才会显示。

样品:

MockHttpServletRequestBuilder

如果测试用@RunWith(SpringRunner.class) @EnableSpringDataWebSupport @WebMvcTest(MyController.class) @Import({WebSecurityConfig.class}) public class MyControllerTest { @Autowired protected MockMvc mockMvc; @Test @WithJwt(principal = "admin", authorities = {"READ_USERS"}) public void readUsersAuthorityCanListUsers() throws Exception { final List<User> users = Arrays.asList(admin, user); when(userRepo.findAll(any(Pageable.class))).thenReturn(new PageImpl<>(users)); this.mockMvc .perform(get("/") .header("Authorization", "Bearer foo")) .andExpect(status().isOk()) .andExpect(jsonPath("$.content", hasSize(users.size()))); } } 修饰,如何对请求构建器进行后处理以自动应用.header("Authorization", "Bearer foo")

1 个答案:

答案 0 :(得分:0)

我结束了对MockMvc和代理方法调用的包装,并添加了Authorization标头。

这对于单个标头来说可能是多余的,但是此MockMvcHelper还设置了内容类型并接受标头,提供了发出简单api调用的快捷方式(获取,发布,放置补丁,使用默认标头删除和序列化)等。

您可以在其他问题的解决方案结尾处查看此包装器:https://stackoverflow.com/a/48540159/619830