728x90
스프링 시큐리티 테스트
로그인 테스트 코드
@Transactional //테스트 후 rollback
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class UserRestControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private UserJPARepository userJPARepository;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
private WebApplicationContext context;
//Spring Security 테스트 환경 구성
@BeforeEach
public void setup(){
mvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
@Test
@WithMockUser
@DisplayName("로그인 성공(가입된 id와 비밀번호)")
public void login_success_test() throws Exception {
//given
//user 생성
User user = User.builder()
.email("user1@nate.com")
.password(passwordEncoder.encode("user1234!"))
.username("user")
.roles("ROLE_USER")
.build();
//저장
userJPARepository.save(user);
//요청 body
UserRequest.LoginDTO loginDTO = new UserRequest.LoginDTO();
loginDTO.setEmail("user1@nate.com");
loginDTO.setPassword("user1234!");
ObjectMapper objectMapper = new ObjectMapper();
String requestData = objectMapper.writeValueAsString(loginDTO);
//jwt Token
String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyMTIzMzZAbmF0ZS5jb20iLCJyb2xlIjoiUk9MRV9VU0VSIiwiaWQiOjEsImV4cCI6MTY4ODg5ODkxNn0.2ovT4QRQHAKFsjHZG1g_bFwC3RN9-3TxdgS_gMm3FKVstqrqPrw6C0VZEwmh5buZzz3ek3Ez_Z3IsNqiVnONcQ";
//when
mvc.perform(
post("/login")
.header("Authorization", "Bearer " + jwtToken)
.contentType(MediaType.APPLICATION_JSON)
.content(requestData))
.andDo(print()) //결과 출력
//then
.andExpect(jsonPath("$.success").value("true"));
}
@Test
@WithMockUser
@DisplayName("로그인 실패 -가입된 id와 잘못된 비밀번호")
public void login_fail_pw_test() throws Exception {
//given
//user 생성
User user = User.builder()
.email("user@nate.com")
.password(passwordEncoder.encode("user1234!"))
.username("user")
.roles("ROLE_USER")
.build();
//저장
userJPARepository.save(user);
//요청 body
UserRequest.LoginDTO loginDTO = new UserRequest.LoginDTO();
loginDTO.setEmail("user@nate.com");
loginDTO.setPassword("wrongpassword!");
ObjectMapper objectMapper = new ObjectMapper();
String requestData = objectMapper.writeValueAsString(loginDTO);
//jwt Token
String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyMTIzMzZAbmF0ZS5jb20iLCJyb2xlIjoiUk9MRV9VU0VSIiwiaWQiOjEsImV4cCI6MTY4ODg5ODkxNn0.2ovT4QRQHAKFsjHZG1g_bFwC3RN9-3TxdgS_gMm3FKVstqrqPrw6C0VZEwmh5buZzz3ek3Ez_Z3IsNqiVnONcQ";
//when
mvc.perform(
post("/login")
.header("Authorization", "Bearer " + jwtToken)
.contentType(MediaType.APPLICATION_JSON)
.content(requestData))
.andDo(print()) //결과 출력
//then
.andExpect(jsonPath("$.success").value("false"));
}
@Test
@WithMockUser
@DisplayName("로그인 실패 - 존재하지 않는 id와 비밀번호 (미가입)")
public void login_fail_unregistered_test() throws Exception {
//given
//user 생성
User user = User.builder()
.email("user@nate.com")
.password(passwordEncoder.encode("user1234!"))
.username("user")
.roles("ROLE_USER")
.build();
//저장
userJPARepository.save(user);
//요청 body
UserRequest.LoginDTO loginDTO = new UserRequest.LoginDTO();
loginDTO.setEmail("newuser@nate.com"); //이미 존재하는 id
loginDTO.setPassword("fake1234!");
ObjectMapper objectMapper = new ObjectMapper();
String requestData = objectMapper.writeValueAsString(loginDTO);
//jwt Token
String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyMTIzMzZAbmF0ZS5jb20iLCJyb2xlIjoiUk9MRV9VU0VSIiwiaWQiOjEsImV4cCI6MTY4ODg5ODkxNn0.2ovT4QRQHAKFsjHZG1g_bFwC3RN9-3TxdgS_gMm3FKVstqrqPrw6C0VZEwmh5buZzz3ek3Ez_Z3IsNqiVnONcQ";
//when
mvc.perform(
post("/login")
.header("Authorization", "Bearer " + jwtToken)
.contentType(MediaType.APPLICATION_JSON)
.content(requestData))
.andDo(print()) //결과 출력
//then
.andExpect(jsonPath("$.success").value("false"));
}
@Test
@WithMockUser
@DisplayName("로그인 실패 - 이메일 형식 검증")
public void login_fail_email_format_test() throws Exception {
//given
//요청 body
UserRequest.LoginDTO loginDTO = new UserRequest.LoginDTO();
loginDTO.setEmail("newusernate.com"); //올바르지 않은 이메일 (@가 없음)
loginDTO.setPassword("user1234!");
ObjectMapper objectMapper = new ObjectMapper();
String requestData = objectMapper.writeValueAsString(loginDTO);
//jwt Token
String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyMTIzMzZAbmF0ZS5jb20iLCJyb2xlIjoiUk9MRV9VU0VSIiwiaWQiOjEsImV4cCI6MTY4ODg5ODkxNn0.2ovT4QRQHAKFsjHZG1g_bFwC3RN9-3TxdgS_gMm3FKVstqrqPrw6C0VZEwmh5buZzz3ek3Ez_Z3IsNqiVnONcQ";
//when
mvc.perform(
post("/login")
.header("Authorization", "Bearer " + jwtToken)
.contentType(MediaType.APPLICATION_JSON)
.content(requestData))
.andDo(print()) //결과 출력
//then
.andExpect(jsonPath("$.success").value("false"));
}
@Test
@WithMockUser
@DisplayName("로그인 실패 - 비밀번호 글자 검증")
public void login_fail_password_character_test() throws Exception {
//given
//요청 body
UserRequest.LoginDTO loginDTO = new UserRequest.LoginDTO();
loginDTO.setEmail("newuser@nate.com");
loginDTO.setPassword("user1234"); //특수문자가 없는 비밀번호
ObjectMapper objectMapper = new ObjectMapper();
String requestData = objectMapper.writeValueAsString(loginDTO);
//jwt Token
String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyMTIzMzZAbmF0ZS5jb20iLCJyb2xlIjoiUk9MRV9VU0VSIiwiaWQiOjEsImV4cCI6MTY4ODg5ODkxNn0.2ovT4QRQHAKFsjHZG1g_bFwC3RN9-3TxdgS_gMm3FKVstqrqPrw6C0VZEwmh5buZzz3ek3Ez_Z3IsNqiVnONcQ";
//when
mvc.perform(
post("/login")
.header("Authorization", "Bearer " + jwtToken)
.contentType(MediaType.APPLICATION_JSON)
.content(requestData))
.andDo(print()) //결과 출력
//then
.andExpect(jsonPath("$.success").value("false"));
}
@Test
@WithMockUser
@DisplayName("로그인 실패 - 인증되지 않은 유저")
public void login_fail_unauth_test() throws Exception {
//given
//요청 body
UserRequest.LoginDTO loginDTO = new UserRequest.LoginDTO();
loginDTO.setEmail("newuser@nate.com");
loginDTO.setPassword("user1234!");
ObjectMapper objectMapper = new ObjectMapper();
String requestData = objectMapper.writeValueAsString(loginDTO);
//when
mvc.perform( //토큰 보내지 않음
post("/login")
.contentType(MediaType.APPLICATION_JSON)
.content(requestData))
.andDo(print()) //결과 출력
//then
.andExpect(jsonPath("$.success").value("false"));
}
@Test
@WithMockUser
@DisplayName("로그인 실패 - 비밀번호 글자수")
public void login_fail_password_length_test() throws Exception {
//given
//요청 body
UserRequest.LoginDTO loginDTO = new UserRequest.LoginDTO();
loginDTO.setEmail("newuser@nate.com");
loginDTO.setPassword("us4!"); //적은 글자수의 비밀번호
ObjectMapper objectMapper = new ObjectMapper();
String requestData = objectMapper.writeValueAsString(loginDTO);
//when
mvc.perform( //토큰 보내지 않음
post("/login")
.contentType(MediaType.APPLICATION_JSON)
.content(requestData))
.andDo(print()) //결과 출력
//then
.andExpect(jsonPath("$.success").value("false"));
}
}
스프링 시큐리티 테스트 환경 구성
@Transactional //테스트 후 rollback
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class UserRestControllerTest {
@Autowired
private MockMvc mvc;
@Autowired //레포지토리
private UserJPARepository userJPARepository;
@Autowired //비밀번호 Encoder
PasswordEncoder passwordEncoder;
@Autowired
private WebApplicationContext context;
//Spring Security 테스트 환경 구성
@BeforeEach
public void setup(){
mvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
}
단위 테스트
@Test
@WithMockUser
@DisplayName("로그인 성공(가입된 id와 비밀번호)")
public void login_success_test() throws Exception {
//given
//user 생성
User user = User.builder()
.email("user1@nate.com")
.password(passwordEncoder.encode("user1234!"))
.username("user")
.roles("ROLE_USER")
.build();
//저장
userJPARepository.save(user);
//요청 body
UserRequest.LoginDTO loginDTO = new UserRequest.LoginDTO();
loginDTO.setEmail("user1@nate.com");
loginDTO.setPassword("user1234!");
ObjectMapper objectMapper = new ObjectMapper();
String requestData = objectMapper.writeValueAsString(loginDTO);
//jwt Token
String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyMTIzMzZAbmF0ZS5jb20iLCJyb2xlIjoiUk9MRV9VU0VSIiwiaWQiOjEsImV4cCI6MTY4ODg5ODkxNn0.2ovT4QRQHAKFsjHZG1g_bFwC3RN9-3TxdgS_gMm3FKVstqrqPrw6C0VZEwmh5buZzz3ek3Ez_Z3IsNqiVnONcQ";
//when
mvc.perform(
post("/login")
.header("Authorization", "Bearer " + jwtToken)
.contentType(MediaType.APPLICATION_JSON)
.content(requestData))
.andDo(print()) //결과 출력
//then
.andExpect(jsonPath("$.success").value("true"));
}
@MockUser : 인증된 유저를 생성한다.
728x90
'Spring > Spring 개발 상식' 카테고리의 다른 글
DTO 생성 방법 (0) | 2023.07.10 |
---|---|
DAO vs DTO vs VO (2) | 2023.07.10 |
DB : 기본키, 외래키, 제약조건 (1) | 2023.07.06 |
Mock test : @AutoConfigureMockMvc, MockMvc, JsonPath (0) | 2023.07.05 |
@Controller, @RestController, @ResponseEntity (0) | 2023.07.05 |