728x90

이전글

 

[Project] 05. SNS 웹 서비스 제작

이전글 https://chordplaylist.tistory.com/219 첫 번째 미션 AWS EC2에 Docker 배포 Gitlab CI & Crontab CD Swagger 회원가입 로그인 포스트 작성, 수정, 삭제, 리스트 추가 JWT Exception Test Code 작성 JWT JWT Exception 처리 [JWT

chordplaylist.tistory.com

첫 번째 미션

  1. AWS EC2에 Docker 배포
  2. Gitlab CI & Crontab CD
  3. Swagger
  4. 회원가입
  5. 로그인
  6. 포스트 작성, 수정, 삭제, 리스트

추가

  1. JWT Exception
  2. Test Code 작성

Test Code

User

UserController Test

...
class UserControllerTest {
    ...
    /* 로그인 */
    @Test
    @DisplayName("로그인 성공")
    void login_success() throws Exception {
        UserDto userDto = UserDto.builder()
                .id(1)
                .userName("jun")
                .password("abcd")
                .userRole(UserRole.USER)
                .build();

        UserLoginRequest request = new UserLoginRequest(userDto.getUserName(), userDto.getPassword());
        UserLoginResponse response = new UserLoginResponse(token);
        given(userService.login(any())).willReturn(response);

        String url = "/api/v1/users/login";
        mockMvc.perform(post(url).with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(request)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.resultCode").exists())
                .andExpect(jsonPath("$.resultCode").value("SUCCESS"))
                .andExpect(jsonPath("$.result.jwt").exists())
                .andExpect(jsonPath("$.result.jwt").value(token))
                .andDo(print());
        verify(userService, times(1)).login(any());
    }
}
...
class UserControllerTest {
    ...

    /* 로그인 */
    ...
    @Test
    @DisplayName("로그인 실패_userName 없음")
    void login_fail_empty_user_name() throws Exception {
        UserDto userDto = UserDto.builder()
                .id(1)
                .userName("jun")
                .password("abcd")
                .userRole(UserRole.USER)
                .build();

        UserLoginRequest request = new UserLoginRequest("abc", "bbcd");

        given(userService.login(any()))
                .willThrow(new SNSAppException(USERNAME_NOT_FOUND, USERNAME_NOT_FOUND.getMessage()));

        String url = "/api/v1/users/login";
        mockMvc.perform(post(url).with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(request)))
                .andExpect(status().isNotFound())
                .andDo(print());
    }
}
 

[04] User Test 코드 작성

이전글 [03] 게시된 포스트 삭제 이전글 [03] 게시된 포스트 수정 이전글 [03] 게시된 모든 포스트 목록 보기 이전글 [03] 포스트 등록 만들기 체크 사항 로그인이 되어있어야 하며, 토큰으로 인증을

chordplaylist.tistory.com

Post

PostController Test

...
class PostControllerTest {
    ...

    /* 포스트 상세 */
    @Test
    @DisplayName("포스트 상세 보기")
    void post_one_detail() throws Exception {
        Post dto = PostFixture.get();
        int postId = dto.getId();

        PostReadResponse response = PostReadResponse.builder()
                .id(dto.getId())
                .title(dto.getTitle())
                .body(dto.getBody())
                .userName(dto.getUser().getUserName())
                .createdAt(time)
                .lastModifiedAt(time)
                .build();

        given(postService.getPost(any())).willReturn(response);

        String url = String.format("/api/v1/posts/%d", postId);

        mockMvc.perform(get(url).with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.resultCode").exists())
                .andExpect(jsonPath("$.resultCode").value("SUCCESS"))
                .andExpect(jsonPath("$.result.id").exists())
                .andExpect(jsonPath("$.result.id").value(1))
                .andExpect(jsonPath("$.result.title").exists())
                .andExpect(jsonPath("$.result.title").value("제목"))
                .andExpect(jsonPath("$.result.body").exists())
                .andExpect(jsonPath("$.result.body").value("내용"))
                .andExpect(jsonPath("$.result.userName").exists())
                .andExpect(jsonPath("$.result.userName").value("chordpli"))
                .andExpect(jsonPath("$.result.createdAt").exists())
                .andExpect(jsonPath("$.result.lastModifiedAt").exists())
                .andDo(print());
        verify(postService, times(1)).getPost(any());

    }
}
...
class PostControllerTest {
    ...
    @Test
    @DisplayName("포스트 작성 실패")
    void post_fail_no_token() throws Exception {
        PostRequest request = new PostRequest("title", "content");

        given(postService.post(any(), any())).willThrow(new SNSAppException(INVALID_PERMISSION, "토큰이 존재하지 않습니다."));

        String url = "/api/v1/posts";

        mockMvc.perform(post(url).with(csrf())
                        .header(HttpHeaders.AUTHORIZATION, "")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(request)))
                .andExpect(status().isUnauthorized())
                .andDo(print());
        verify(postService, times(1)).post(any(), any());
    }
}
 

[04] Post Test 코드 작성 - 1 (Controller Test)

이전글 [04] User Test 코드 작성 이전글 [03] 게시된 포스트 삭제 이전글 [03] 게시된 포스트 수정 이전글 [03] 게시된 모든 포스트 목록 보기 이전글 [03] 포스트 등록 만들기 체크 사항 로그인이 되어

chordplaylist.tistory.com

PostService Test

class PostServiceTest {
    ...
    /* 포스트 상세 */
    @Test
    @DisplayName("조회 성공")
    void success_get_post() {
        Post fixture = PostFixture.get();

        when(postRepository.findById(any())).thenReturn(Optional.of(fixture));
        PostReadResponse response = postService.getPost(fixture.getId());
        assertEquals(fixture.getUser().getUserName(), response.getUserName());
    }
}
class PostServiceTest {
    ...
    /* 포스트 삭제 */
    @Test
    @DisplayName("삭제 실패_유저가 존재하지 않음")
    void fail_delete_post_not_exist_user() {
        Post fixture = PostFixture.get();

        when(userRepository.findByUserName(any())).thenReturn(Optional.empty());

        SNSAppException exception
                = Assertions.assertThrows(SNSAppException.class,
                () -> postService.deletePost(fixture.getId(), fixture.getUser().getUserName()));
        Assertions.assertEquals(ErrorCode.USERNAME_NOT_FOUND, exception.getErrorCode());
    }
}
 

[04] Post Test 코드 작성 - 2 (Service Test)

이전글 [04] Post Test 코드 작성 - 1 (Controller Test) 이전글 [04] User Test 코드 작성 이전글 [03] 게시된 포스트 삭제 이전글 [03] 게시된 포스트 수정 이전글 [03] 게시된 모든 포스트 목록 보기 이전글 [03]

chordplaylist.tistory.com

다음글

 

 

[Project] 07. SNS 웹 서비스 제작

이전글 [Project] 06. SNS 웹 서비스 제작 이전글 [Project] 05. SNS 웹 서비스 제작 이전글 https://chordplaylist.tistory.com/219 첫 번째 미션 AWS EC2에 Docker 배포 Gitlab CI & Crontab CD Swagger 회원가입 로그인 포스트 작

chordplaylist.tistory.com

 

반응형
코드플리