반응형
의존성 추가
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
스프링 시큐리티 테스트
- @WithMockUser 어노테이션 이용
- with() 메서드 이용
package me.whiteship.demospringsecurityform.account;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
class AccountControllerTest {
@Autowired
MockMvc mockMvc;
// with() 메서드
@Test
public void admin_admin() throws Exception {
mockMvc.perform(get("/admin").with(user("user1").roles("ADMIN")))
.andDo(print())
.andExpect(status().isOk());
}
// 어노테이션 사용
@WithMockUser(username = "user1", roles = "ADMIN")
@Test
public void admin_admin() throws Exception {
mockMvc.perform(get("/admin"))
.andDo(print())
.andExpect(status().isOk());
}
}
반응형
'Spring Security' 카테고리의 다른 글
Spring Security 기본 셋팅 (0) | 2021.01.04 |
---|