브라우저에서 직접 요청을 하여 테스트 하기 보다는 테스트 코드로 테스트 해보자.
의존성 추가
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
<version>${spring-security.version}</version>
</dependency>
테스트 코드 작성
기본 코드
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AccountControllerTest {
}
가짜 유저를 이용해서 mocking 하여 요청을 한다. 유저를 등록하는 것이 아니다. 가정을 하는 것이다.
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AccountControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void index_anonymous() throws Exception {
mockMvc.perform(get("/").with(anonymous()))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void index_user() throws Exception {
mockMvc.perform(get("/").with(user("cmlee").roles("USER")))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void admin_anonymous() throws Exception {
mockMvc.perform(get("/admin").with(anonymous()))
.andDo(print())
.andExpect(status().isUnauthorized());
}
@Test
public void admin_user() throws Exception {
mockMvc.perform(get("/admin").with(user("cmlee").roles("USER")))
.andDo(print())
.andExpect(status().isForbidden());
}
@Test
public void admin_admin() throws Exception {
mockMvc.perform(get("/admin").with(user("admin").roles("ADMIN")))
.andDo(print())
.andExpect(status().isOk());
}
}
password도 넣을 수 있지만 의미가 없다.
애노테이션을 사용하는 방법
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AccountControllerTest {
@Autowired
MockMvc mockMvc;
@Test
@WithAnonymousUser
public void index_anonymous() throws Exception {
mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
@WithMockUser(username = "cmlee", roles = "USER")
public void index_user() throws Exception {
mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
@WithAnonymousUser
public void admin_anonymous() throws Exception {
mockMvc.perform(get("/admin"))
.andDo(print())
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(username = "cmlee", roles = "USER")
public void admin_user() throws Exception {
mockMvc.perform(get("/admin"))
.andDo(print())
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(username = "admin", roles = "ADMIN")
public void admin_admin() throws Exception {
mockMvc.perform(get("/admin").with(user("admin").roles("ADMIN")))
.andDo(print())
.andExpect(status().isOk());
}
}