如何根据测试注释向 MockMvc 请求添加 header?
How to add a header to a MockMvc request, depending on test annotation?
作为 的跟进,我想知道如何透明地将 "Authorization" header 添加到 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())));
}
}
如果测试用 @WithJwt
装饰,如何 post-process 请求生成器自动应用 .header("Authorization", "Bearer foo")
?
我结束了包装 MockMvc
和代理方法调用,添加了 Authorization
header.
对于单个 header,这将是 over-kill,但此 MockMvcHelper
还设置 content-type 并接受 headers,提供发布简单的快捷方式api 调用(获取、post、放置补丁、默认删除 headers 和序列化)等
您可以在其他问题的解决方案末尾查看此包装器:https://whosebug.com/a/48540159/619830
作为 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())));
}
}
如果测试用 @WithJwt
装饰,如何 post-process 请求生成器自动应用 .header("Authorization", "Bearer foo")
?
我结束了包装 MockMvc
和代理方法调用,添加了 Authorization
header.
对于单个 header,这将是 over-kill,但此 MockMvcHelper
还设置 content-type 并接受 headers,提供发布简单的快捷方式api 调用(获取、post、放置补丁、默认删除 headers 和序列化)等
您可以在其他问题的解决方案末尾查看此包装器:https://whosebug.com/a/48540159/619830