Advertisement
Guest User

Untitled

a guest
Jul 30th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. @Configuration
  2. @EnableWebSecurity
  3. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  4.  
  5. @Override
  6. protected void configure(HttpSecurity http) throws Exception {
  7. http.authorizeRequests().antMatchers("/admin*").access("hasRole('ADMIN')").antMatchers("/**").permitAll().and().formLogin();
  8. }
  9.  
  10. @Autowired
  11. public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  12. auth.inMemoryAuthentication().withUser("user").password("password").roles("ADMIN");
  13. }
  14. }
  15.  
  16. @RunWith(SpringRunner.class)
  17. @WebMvcTest(value = ExampleController.class)
  18. public class ExampleControllerMockMVCTest {
  19.  
  20. @Autowired
  21. private MockMvc mockMvc;
  22.  
  23. @Test
  24. public void indexTest() throws Exception {
  25. mockMvc.perform(get("/"))
  26. .andExpect(status().isOk())
  27. .andExpect(view().name("index"));
  28. }
  29.  
  30. @Test
  31. public void adminTestWithoutAuthentication() throws Exception {
  32. mockMvc.perform(get("/admin"))
  33. .andExpect(status().is3xxRedirection()); //login form redirect
  34. }
  35.  
  36. @Test
  37. @WithMockUser(username="example", password="password", roles={"ANONYMOUS"})
  38. public void adminTestWithBadAuthentication() throws Exception {
  39. mockMvc.perform(get("/admin"))
  40. .andExpect(status().isForbidden());
  41. }
  42.  
  43. @Test
  44. @WithMockUser(username="user", password="password", roles={"ADMIN"})
  45. public void adminTestWithAuthentication() throws Exception {
  46. mockMvc.perform(get("/admin"))
  47. .andExpect(status().isOk())
  48. .andExpect(view().name("admin"))
  49. .andExpect(model().attributeExists("name"))
  50. .andExpect(model().attribute("name", is("user")));
  51. }
  52. }
  53.  
  54. @RunWith(SpringRunner.class)
  55. @SpringBootTest(webEnvironment = WebEnvironment.MOCK)
  56. @AutoConfigureMockMvc
  57. public class ExampleControllerSpringBootTest {
  58.  
  59. @Autowired
  60. private MockMvc mockMvc;
  61.  
  62. // tests
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement