[英]How to test stateless with MockMvc and Mockito
I recently inherited some java code, that needs to switch to stateless in HttpSecurity configuration: 我最近继承了一些Java代码,需要在HttpSecurity配置中将其切换为无状态:
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
After that, some tests using MockMvc failed. 此后,使用MockMvc的某些测试失败。 I know @WithMockUser will not work with stateless, so what should I change to get it pass?
我知道@WithMockUser将无法在无状态的情况下工作,那么我应该如何更改以使其通过? Here is an example test:
这是一个示例测试:
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders.standaloneSetup(apAdminController)
.apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.build();
storeUser = new StoreUser();
storeUser.setUsername("smith");
storeUser.setEnabled(true);
}
@Test
@WithMockUser(roles = "ADMIN")
public void testViewStoreUserWithAdmin() {
try {
mockMvc.perform(
get("{resource}/1", RESOURCE).with(testSecurityContext()))
.andDo(print())
.andExpect(status().isOk());
} catch (Exception e) {
fail("Test failed: " + e.getMessage());
}
}
It took me a long time to find answers, here is what I ended up with, in case anyone is struggling: 我花了很长时间才能找到答案,这是我最终得到的结果,以防万一有人在挣扎:
After changing SessionCreationPolicy from 'If_REQUIRED' or 'ALWAYS' to 'STATELESS' on the tests: replace import .SecurityMockMvcRequestPostProcessors.testSecurityContext;
在测试中将SessionCreationPolicy从'If_REQUIRED'或'ALWAYS'更改为'STATELESS'之后:替换import
.SecurityMockMvcRequestPostProcessors.testSecurityContext;
to import .SecurityMockMvcRequestPostProcessors.user;
导入
.SecurityMockMvcRequestPostProcessors.user;
and use this in the setup: 并在设置中使用它:
this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilters(springSecurityFilterChain)
.build();
Remove all the annotation @WithMockUser
and finally, change 删除所有注释
@WithMockUser
,最后更改
get("{resource}", RESOURCE).with(testSecurityContext()))
to get("{resource}", RESOURCE).with(user("admin").roles("ADMIN")))
以
get("{resource}", RESOURCE).with(user("admin").roles("ADMIN")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.