SecurityMockMvcResultHandlers

Spring Security 提供一些 ResultHandler 的实现。为使用 Spring Security 的 ResultHandler 的实现确保已使用了以下静态导入:

Spring Security provides a few `ResultHandler`s implementations. In order to use Spring Security’s `ResultHandler`s implementations ensure the following static import is used:

import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultHandlers.*;

Exporting the SecurityContext

通常我们希望查询一个存储库来查看某些 MockMvc 请求是否实际保存在数据库中。在某些情况下,我们的存储库查询使用 Spring Data Integration 根据当前用户的用户名或任何其他属性过滤结果。让我们看一个示例:

Often times we want to query a repository to see if some MockMvc request actually persisted in the database. In some cases our repository query uses the Spring Data Integration to filter the results based on current user’s username or any other property. Let’s see an example:

一个数据仓库接口:

A repository interface:

private interface MessageRepository extends JpaRepository<Message, Long> {
	@Query("SELECT m.content FROM Message m WHERE m.sentBy = ?#{ principal?.name }")
	List<String> findAllUserMessages();
}

我们的测试场景:

Our test scenario:

mvc
	.perform(post("/message")
		.content("New Message")
		.contentType(MediaType.TEXT_PLAIN)
	)
	.andExpect(status().isOk());

List<String> userMessages = messageRepository.findAllUserMessages();
assertThat(userMessages).hasSize(1);

此测试无法通过,因为在我们的请求完成后,SecurityContextHolder 将被过滤器链清除。然后,我们可以将 TestSecurityContextHolder 导出到 SecurityContextHolder 中,并按需要使用它:

This test won’t pass because after our request finishes, the SecurityContextHolder will be cleared out by the filter chain. We can then export the TestSecurityContextHolder to our SecurityContextHolder and use it as we want:

mvc
	.perform(post("/message")
		.content("New Message")
		.contentType(MediaType.TEXT_PLAIN)
	)
	.andDo(exportTestSecurityContext())
	.andExpect(status().isOk());

List<String> userMessages = messageRepository.findAllUserMessages();
assertThat(userMessages).hasSize(1);

记住在测试之间清除 SecurityContextHolder,否则可能在它们之间泄漏

Remember to clear the SecurityContextHolder between your tests, or it may leak amongst them