2
0

result-handlers.adoc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. = SecurityMockMvcResultHandlers
  2. Spring Security provides a few ``ResultHandler``s implementations.
  3. In order to use Spring Security's ``ResultHandler``s implementations ensure the following static import is used:
  4. [source,java]
  5. ----
  6. import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultHandlers.*;
  7. ----
  8. == Exporting the SecurityContext
  9. Often times we want to query a repository to see if some `MockMvc` request actually persisted in the database.
  10. In some cases our repository query uses the xref:features/integrations/data.adoc[Spring Data Integration] to filter the results based on current user's username or any other property.
  11. Let's see an example:
  12. A repository interface:
  13. [source,java]
  14. ----
  15. private interface MessageRepository extends JpaRepository<Message, Long> {
  16. @Query("SELECT m.content FROM Message m WHERE m.sentBy = ?#{ principal?.name }")
  17. List<String> findAllUserMessages();
  18. }
  19. ----
  20. Our test scenario:
  21. [source,java]
  22. ----
  23. mvc
  24. .perform(post("/message")
  25. .content("New Message")
  26. .contentType(MediaType.TEXT_PLAIN)
  27. )
  28. .andExpect(status().isOk());
  29. List<String> userMessages = messageRepository.findAllUserMessages();
  30. assertThat(userMessages).hasSize(1);
  31. ----
  32. This test won't pass because after our request finishes, the `SecurityContextHolder` will be cleared out by the filter chain.
  33. We can then export the `TestSecurityContextHolder` to our `SecurityContextHolder` and use it as we want:
  34. [source,java]
  35. ----
  36. mvc
  37. .perform(post("/message")
  38. .content("New Message")
  39. .contentType(MediaType.TEXT_PLAIN)
  40. )
  41. .andDo(exportTestSecurityContext())
  42. .andExpect(status().isOk());
  43. List<String> userMessages = messageRepository.findAllUserMessages();
  44. assertThat(userMessages).hasSize(1);
  45. ----
  46. [NOTE]
  47. ====
  48. Remember to clear the `SecurityContextHolder` between your tests, or it may leak amongst them
  49. ====