Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Configuration
- @EnableWebSecurity
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().antMatchers("/admin*").access("hasRole('ADMIN')").antMatchers("/**").permitAll().and().formLogin();
- }
- @Autowired
- public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication().withUser("user").password("password").roles("ADMIN");
- }
- }
- @RunWith(SpringRunner.class)
- @WebMvcTest(value = ExampleController.class)
- public class ExampleControllerMockMVCTest {
- @Autowired
- private MockMvc mockMvc;
- @Test
- public void indexTest() throws Exception {
- mockMvc.perform(get("/"))
- .andExpect(status().isOk())
- .andExpect(view().name("index"));
- }
- @Test
- public void adminTestWithoutAuthentication() throws Exception {
- mockMvc.perform(get("/admin"))
- .andExpect(status().is3xxRedirection()); //login form redirect
- }
- @Test
- @WithMockUser(username="example", password="password", roles={"ANONYMOUS"})
- public void adminTestWithBadAuthentication() throws Exception {
- mockMvc.perform(get("/admin"))
- .andExpect(status().isForbidden());
- }
- @Test
- @WithMockUser(username="user", password="password", roles={"ADMIN"})
- public void adminTestWithAuthentication() throws Exception {
- mockMvc.perform(get("/admin"))
- .andExpect(status().isOk())
- .andExpect(view().name("admin"))
- .andExpect(model().attributeExists("name"))
- .andExpect(model().attribute("name", is("user")));
- }
- }
- @RunWith(SpringRunner.class)
- @SpringBootTest(webEnvironment = WebEnvironment.MOCK)
- @AutoConfigureMockMvc
- public class ExampleControllerSpringBootTest {
- @Autowired
- private MockMvc mockMvc;
- // tests
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement