본문 바로가기

프로젝트/멋사 개인 프로젝트 (mutsa-SNS)

[19] mutsa-SNS-2 2일차 - (2) 좋아요 기능 test code

앞서 만든 좋아요 기능이 제대로 작동하는지 test code를 통해 검증해보았다.

  • 좋아요 누르기 성공
  • 좋아요 누르기 실패 - 로그인 하지 않은 경우
  • 좋아요 누르기 실패 - 해당 Post가 없는 경우

 

1. PostControllerTest

@WebMvcTest(PostController.class)
class PostControllerTest {
    @Autowired
    MockMvc mockMvc;

    @MockBean
    PostService postService;

    @Autowired
    ObjectMapper objectMapper;
    
    ...
    
    @Test
    @DisplayName("좋아요 누르기 성공")
    @WithMockUser
    void like_do_success() throws Exception {

        when(postService.doLike(any(), any()))
                .thenReturn("좋아요를 눌렀습니다.");

        mockMvc.perform(post("/api/v1/posts/1/likes")
                .with(csrf())
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.resultCode").value("SUCCESS"))
                .andExpect(jsonPath("$.result").value("좋아요를 눌렀습니다."))
                .andExpect(status().isOk())
                .andDo(print());

    }

    @Test
    @DisplayName("좋아요 누르기 실패 - 로그인 하지 않은 경우")
    @WithAnonymousUser
    void like_do_fail_1() throws Exception {

        mockMvc.perform(post("/api/v1/posts/1/likes")
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isUnauthorized())
                .andDo(print());

    }

    @Test
    @DisplayName("좋아요 누르기 실패 - 해당 Post가 없는 경우")
    @WithMockUser
    void like_do_fail_2() throws Exception {

        when(postService.doLike(any(), any()))
                .thenThrow(new AppException(ErrorCode.POST_NOT_FOUND, ""));


        mockMvc.perform(post("/api/v1/posts/1/likes")
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().is(ErrorCode.POST_NOT_FOUND.getStatus().value()))
                .andExpect(jsonPath("$.resultCode").value("ERROR"))
                .andExpect(jsonPath("$.result.message").value(ErrorCode.POST_NOT_FOUND.getMessage()))
                .andExpect(jsonPath("$.result.errorCode").value(ErrorCode.POST_NOT_FOUND.name()))
                .andDo(print());

    }

}

테스트 코드의 로직은 기존 post와 comment와 거의 동일하다.