본문 바로가기

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

[10] mutsa-SNS 5일차 - (1) Post 조회 기능 TestCode 추가

post 조회 기능에 대한 testCode를 추가하였다.

postController와 postService에 대하여 testCode를 추가하였다.

 

1. PostControllerTest

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

    @MockBean
    PostService postService;

    @Autowired
    ObjectMapper objectMapper;

    //포스트 상세 테스트
    @Test
    @DisplayName("1번글 조회 성공")
    @WithMockUser
    void post_detail_success() throws Exception {

        PostDto postDto = PostDto.builder()
                .id(1)
                .title("aaa")
                .body("bbb")
                .userName("ccc")
                .build();

        when(postService.detailPost(any())).thenReturn(postDto);

        mockMvc.perform(get("/api/v1/posts/1")
                        .with(csrf()))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.result.id").value(postDto.getId()))
                .andExpect(jsonPath("$.result.title").value(postDto.getTitle()))
                .andExpect(jsonPath("$.result.body").value(postDto.getBody()))
                .andExpect(jsonPath("$.result.userName").value(postDto.getUserName()))
                .andDo(print());

    }

    @Test
    @DisplayName("최신글 정렬 - pageable test")
    @WithMockUser
    void post_all_success() throws Exception {
        
        mockMvc.perform(get("/api/v1/posts")
                        .param("sort", "createdAt,desc"))
                .andExpect(status().isOk())
                .andDo(print());

        ArgumentCaptor<Pageable> pageableCaptor = ArgumentCaptor.forClass(Pageable.class);
        verify(postService).getPostAll(pageableCaptor.capture());
        PageRequest pageable = (PageRequest) pageableCaptor.getValue();

        assertEquals(Sort.by(DESC, "createdAt"), pageable.getSort());
        
    }


}

포스트 상세 조회 Test

  • postService가 postDto를 return하도록 설정
  • /api/v1/posts/1 에 조회하였을 때, postDto의 id, title, body, userName과 동일한지 검증

최신글 정렬 - pageable test

  • controller에서 사용한 pageable의 sort 방식 검증 (createdAt의 시간으로 최신순 정렬)

<Reference>

https://reflectoring.io/spring-boot-paging/

 

Paging with Spring Boot

An in-depth look at the paging support provided by Spring Data for querying Spring Web MVC controllers and Spring Data repositories.

reflectoring.io

https://stackoverflow.com/questions/58839592/mockito-with-pageable-object

 

Mockito with Pageable object

I have a below code. public static Pageable defaultSort(Pageable currentPageable, String defaultSort) { return defaultSort(currentPageable, defaultSort, Sort.Direction.ASC); } pub...

stackoverflow.com

https://donghyeon.dev/spring/2019/03/28/Spring-%EC%BB%A8%ED%8A%B8%EB%A1%A4%EB%9F%AC-%ED%85%8C%EC%8A%A4%ED%8A%B8%EB%A5%BC-%EC%9C%84%ED%95%9C-MockMvc/

 

MockMvc

시작하기 전

donghyeon.dev

 

2. PostServiceTest

public class PostServiceTest {

    PostService postService;

    PostRepository postRepository = mock(PostRepository.class);
    UserRepository userRepository = Mockito.mock(UserRepository.class);

    @BeforeEach
    void setUp() {
        postService = new PostService(postRepository, userRepository);

    }

    @Test
    @DisplayName("조회 성공")
    void success_post_get() {

        User user = User.builder()
                .id(1)
                .userName("userName")
                .password("password")
                .role(UserRole.USER)
                .build();

        Post post = Post.builder()
                .id(1)
                .user(user)
                .title("title")
                .body("body")
                .build();


        given(postRepository.findById(post.getId())).willReturn(Optional.of(post));

        PostDto postDto = postService.detailPost(post.getId());
        //postDto userName == User userName
        assertEquals(user.getUserName(), postDto.getUserName());


    }

}

PostDto의 userName과  test 클래스의 포스트의 작성자의 이름이 동일한지 체크

 

<전체 Refercence>

https://reflectoring.io/spring-boot-paging/
https://stackoverflow.com/questions/58839592/mockito-with-pageable-object
https://donghyeon.dev/spring/2019/03/28/Spring-%EC%BB%A8%ED%8A%B8%EB%A1%A4%EB%9F%AC-%ED%85%8C%EC%8A%A4%ED%8A%B8%EB%A5%BC-%EC%9C%84%ED%95%9C-MockMvc/