|
| 1 | +package org.baeldung.web; |
| 2 | + |
| 3 | +import org.junit.Before; |
| 4 | +import org.junit.Test; |
| 5 | +import org.junit.runner.RunWith; |
| 6 | +import org.springframework.beans.factory.annotation.Autowired; |
| 7 | +import org.springframework.boot.test.context.SpringBootTest; |
| 8 | +import org.springframework.test.context.ContextConfiguration; |
| 9 | +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; |
| 10 | +import org.springframework.test.context.web.WebAppConfiguration; |
| 11 | +import org.springframework.test.web.servlet.MockMvc; |
| 12 | +import org.springframework.test.web.servlet.setup.MockMvcBuilders; |
| 13 | +import org.springframework.web.context.WebApplicationContext; |
| 14 | + |
| 15 | +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; |
| 16 | +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; |
| 17 | +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; |
| 18 | +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; |
| 19 | +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; |
| 20 | +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
| 21 | + |
| 22 | +@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration @SpringBootTest public class LiveTest { |
| 23 | + @Autowired private WebApplicationContext context; |
| 24 | + |
| 25 | + private MockMvc mvc; |
| 26 | + |
| 27 | + @Before public void setup() { |
| 28 | + mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); |
| 29 | + } |
| 30 | + |
| 31 | + @Test public void givenUnauthenticatedUser_whenAccessingMainPage_thenRedirect() throws Exception { |
| 32 | + mvc.perform(get("/")).andExpect(status().is3xxRedirection()); |
| 33 | + } |
| 34 | + |
| 35 | + @Test public void givenValidUsernameAndPassword_whenLogin_thenOK() throws Exception { |
| 36 | + mvc.perform(formLogin("/login").user("user").password("pass")).andExpect(authenticated()); |
| 37 | + } |
| 38 | + |
| 39 | + @Test public void givenAuthenticatedAdmin_whenAccessingMainPage_thenOK() throws Exception { |
| 40 | + mvc.perform(get("/").with(user("admin").password("pass").roles("ADMIN"))).andExpect(status().isOk()); |
| 41 | + } |
| 42 | +} |
0 commit comments