본문 바로가기
스프링과 JPA 기반 웹 어플리케이션 개발/1부 (개발환경, 회원가입, 로그인, 계정설정)

18. 로그인 / 로그아웃 테스트

by Backchus 2020. 4. 20.

테스트 요점 정리

  • 폼 서브밋 요청(post)은 반드시 .with(csrf())를 추가할 것.
  • .andExpect(authenticated()) 또는 .andExprect(unauthenticated())로 인증 여부를 확인할 수 있다.
  • 리다이렉트 응답은 .andExpect(status().is3xxRedirection())로 확인할 수 있다.
  • 리다이렉트 URL은 .andExpect(redirectUrl())로 확인할 수 있다.
  • JUnit5의 @BeforeEach와 @AfterEach.
  • 임의로 로그인 된 사용자가 필요한 경우에는 @WithMockUser.

 

테스트 코드

package me.weekbelt.studyolle.main;

@SpringBootTest
@AutoConfigureMockMvc
class MainControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Autowired
    AccountService accountService;

    @Autowired
    AccountRepository accountRepository;

    @BeforeEach
    public void beforeEach() {
        // 회원 가입
        SignUpForm signUpForm = new SignUpForm();
        signUpForm.setNickname("joohyuk");
        signUpForm.setEmail("vfrvfr4207@hanmail.net");
        signUpForm.setPassword("12345678");
        accountService.processNewAccount(signUpForm);
    }

    @AfterEach
    public void afterEach() {
        // 저장된 회원 모두 삭제
        accountRepository.deleteAll();
    }

    @DisplayName("이메일로 로그인 성공")
    @Test
    public void login_with_email() throws Exception {
        mockMvc.perform(post("/login")
                .param("username", "vfrvfr4207@hanmail.net")
                .param("password", "12345678")
                .with(csrf()))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("/"))
                .andExpect(authenticated().withUsername("joohyuk"));
    }

    @DisplayName("이름으로 로그인 성공")
    @Test
    public void login_with_nickname() throws Exception {
        mockMvc.perform(post("/login")
                .param("username", "joohyuk")
                .param("password", "12345678")
                .with(csrf()))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("/"))
                .andExpect(authenticated().withUsername("joohyuk"));
    }

    @DisplayName("로그인 실패")
    @Test
    public void login_fail() throws Exception {
        mockMvc.perform(post("/login")
                .param("username", "1111111")
                .param("password", "00000000000")
                .with(csrf()))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("/login?error"))
                .andExpect(unauthenticated());
    }

    @DisplayName("로그아웃")
    @Test
    public void logout() throws Exception {
        mockMvc.perform(post("/logout")
                .with(csrf()))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("/"))
                .andExpect(unauthenticated());
    }
}

 

 

참고: https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-JPA-%EC%9B%B9%EC%95%B1#

 

스프링과 JPA 기반 웹 애플리케이션 개발 - 인프런

이 강좌에서 여러분은 실제로 운영 중인 서비스를 스프링, JPA 그리고 타임리프를 비롯한 여러 자바 기반의 여러 오픈 소스 기술을 사용하여 웹 애플리케이션을 개발하는 과정을 학습할 수 있습니다. 이 강좌를 충분히 학습한다면 여러분 만의 웹 서비스를 만들거나 취직에 도움이 될만한 포트폴리오를 만들 수 있을 겁니다. 활용 웹 개발 프레임워크 및 라이브러리 Java Spring Spring Boot Spring Data JPA Thymeleaf 온라인 강의 스

www.inflearn.com