我正在尝试测试某些网址是否只有具有特定权限的授权用户才能访问。因为我有自己的UserDetails
,所以我按照the docs
@WithUserDetails
注释我的测试
我的测试类看起来像:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class, ConfigTest.class }, webEnvironment =
WebEnvironment.RANDOM_PORT)
@Transactional
public class SecurityIntegrationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
}
@Test
@WithUserDetails(userDetailsServiceBeanName="myUserDetailsService")
public void testTemp() throws Exception {
this.mockMvc.perform( get("/")).andDo(print()).andExpect(status().isOk());
}
}
Config中的UserDetails Bean如下所示:
@Configuration
public class ConfigTest extends WebMvcConfigurerAdapter {
public ConfigTest() {
super();
}
@Bean
public UserDetailsService myUserDetailsService() {
return new MyUserDetailsService();
}
}
如果我尝试运行测试,我会得到一个例外:
TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener@1ad535f] to process 'before' execution of test method [public void org.trip.test.SecurityIntegrationTest.testTemp() throws java.lang.Exception] for test instance [org.trip.test.SecurityIntegrationTest@167181f]
j.l.IllegalStateException: Unable to create SecurityContext using @org.springframework.security.test.context.support.WithUserDetails(userDetailsServiceBeanName=myUserDetailsService, value=user)
我想这意味着此处合并@Before
和@WithUserDetails
会出现问题。我也尝试用@Before
替换@BeforeTransaction
,但这没有帮助。
我不知道如何解决这个问题,所以非常感谢任何帮助/建议/想法。
PS:匿名运行相同的文本(没有@WithUserDetails
)可以正常运行。