📢 좋아요 개수를 리턴하는 기능을 구현하자.
GET /posts/{postsId}/likes
{
"resultCode":"SUCCESS",
"result": 0
}
<@Test
@DisplayName("좋아요 개수 리턴 성공")
@WithMockUser
void like_count_SUCCESS() throws Exception {
when(likeService.likeCount(any()))
.thenReturn(3L);
mockMvc.perform(get("/api/v1/posts/1/likes")
.with(csrf())
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
@Test
@DisplayName("좋아요 카운트 리턴 실패 : 포스트가 없는 경우")
@WithMockUser
void like_count_FAIL_post() throws Exception {
when(likeService.likeCount(any()))
.thenThrow(new AppException(ErrorCode.POST_NOT_FOUND, ErrorCode.POST_NOT_FOUND.getMessage()));
mockMvc.perform(get("/api/v1/posts/1/likes")
.with(csrf()))
.andDo(print())
.andExpect(status().isNotFound());
}
@Test
@DisplayName("좋아요 카운트 리턴 성공")
void like_count_SUCCESS() {
when(postRepository.findById(any()))
.thenReturn(Optional.of(post));
assertDoesNotThrow(() -> likeService.likeCount(post.getId()));
}
@Test
@DisplayName("좋아요 카운트 리턴 실패 : 포스트가 없는 경우")
void like_count_FAIL_post() {
when(postRepository.findById(any()))
.thenReturn(Optional.empty());
AppException exception = assertThrows(AppException.class, () -> likeService.likeCount(post.getId()));
assertEquals(ErrorCode.POST_NOT_FOUND, exception.getErrorCode());
}
@GetMapping
public ResponseEntity<Response> likeCount(@PathVariable Long postId) {
Long likeCount = likeService.likeCount(postId);
return ResponseEntity.ok().body(Response.of("SUCCESS", likeCount));
}
public Long likeCount(Long postId) {
//포스트 체크
Post findPost = AppUtil.findPost(postRepository, postId);
//좋아요 갯수 리턴
return findPost.getLikes().stream().count();
}