我们可以在测试中手动注入 Spring Security 的“Authentication”对象,以便进行身份验证。以下是一个示例:
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private Authentication authentication;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
authentication = new UsernamePasswordAuthenticationToken("username", "password");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
@Test
public void secureEndpointTest() throws Exception {
mockMvc.perform(get("/secureEndpoint"))
.andExpect(status().isOk());
}
在此示例中,我们首先将当前用户的身份信息注入“Authentication”对象,然后在测试方法中使用 MockMvc 访问安全端点。由于身份验证已经注入,因此测试我们可以成功通过并获得“isOk”响应状态。