on
26. 프로필 수정 테스트
26. 프로필 수정 테스트
728x90
인증된 사용자가 접근할 수 있는 기능 테스트하기
실제 DB에 저장되어 있는 정보에 대응하는 인증된 Authentication이 필요하다.
@WithMockUser로는 처리할 수 없다.
인증된 사용자를 제공할 커스텀 애노테이션 만들기
@BeforeEach void beforeEach() { SignUpForm signUpForm = new SignUpForm(); signUpForm.setNickname("jungi"); signUpForm.setEmail("[email protected]"); signUpForm.setPassword("12345678!"); accountService.processNewAccount(signUpForm); } @WithUserDetails(value = "devjun", setupBefore = TestExecutionEvent.TEST_EXECUTION) // setupBefore -> 실행 순서 정해줌 BeforeEach -> WithUserDetails // But Bug라서 WithUserDetails -> BeforeEach 순으로 실행됨 @DisplayName("프로필 수정하기 - 입력값 정상") @Test void updateProfile() throws Exception { String bio = "짧은 소개를 수정하는 경우"; mockMvc.perform(post(SettingsController.SETTINGS_PROFILE_URL) .param("bio",bio) .with(csrf())) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(SettingsController.SETTINGS_PROFILE_URL)) .andExpect(flash().attributeExists("message")); Account devjun = accountRepository.findByNickname("devjun"); assertEquals(bio, devjun.getBio()); }
setupBefore = TestExecutionEvent.TEST_EXECUTION가 Bug걸려서 데이터 없다고 나오는 모습
커스텀 애노테이션 생성
@Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithAccountSecurityContextFacotry.class) public @interface WithAccount { String value(); }
SecurityContextFactory 구현
public class WithAccountSecurityContextFacotry implements WithSecurityContextFactory { // 빈을 주입 받을 수 있다. // Authentication 만들고 SecurityuContext에 넣어주기 UserDetails principal = accountService.loadUserByUsername(nickname); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); }
실습
from http://devjun.tistory.com/249 by ccl(A) rewrite - 2021-12-24 01:01:55