본문 바로가기
CRUD 게시판

RestApi 게시판 CRUD 만들기 (4) - Controller Test

by YoonJong 2022. 10. 12.
728x90

Controller 테스트를 생성

 

가장 윗부분 설정 부분

@SpringBootTest
@AutoConfigureMockMvc
class PostControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Autowired
    PostRepository postRepository;

    @Autowired
    ObjectMapper objectMapper;

    @BeforeEach
    void clean() {
        postRepository.deleteAll();
    }
}
  • MockMvc를 사용해야 하므로 @AutoConfigureMockMvc 를 선언해준다.
  • MockMvc와 postRespository , String 객체로 만들어주기 위한 ObjectMapper 를 주입시켜준다
  • @BeforeEach를 이용해 각 테스트 실행 전 postRepository 가 초기화(삭제)될 수 있도록 한다.
  •  

테스트 시, Mockmvc 에 관련된 메소드가 반복되면서 사용된다. 

 

post 로  /posts 에 요청하겠다 라는 의미 

mockMvc.perform(post("/posts")

Json 형식으로 데이터를 보낸다는 의미

.contentType(APPLICATION_JSON)

본문의 내용은 updatePostDto 안의 내용 -> String 형태

.content(objectMapper.writeValueAsString(updatePostDto)))

기대되는 응답 코드 

.andExpect(status().isOk())

화면에 결과를 출력

.andDo(print());

@Test
@DisplayName("/posts 게시글 작성")
void create() throws Exception {
    Post post = Post.builder()
            .title("제목")
            .content("내용")
            .build();

    mockMvc.perform(post("/posts")
            .contentType(APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(post)))
            .andExpect(status().isOk())
            .andDo(print());
}
@Test
@DisplayName("/posts 게시글 전체조회")
void findAll() throws Exception {
    for (int i = 1; i <= 5; i++) {
        postRepository.save(Post.builder()
                .title("제목 " + i)
                .content("내용 " + i)
                .build());
    }

    mockMvc.perform(get("/posts")
            .contentType(APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());

    assertThat(postRepository.findAll().size()).isEqualTo(5);
}
@Test
@DisplayName("/posts/{id} 게시글 단건조회")
void findOne() throws Exception {
    Post post = Post.builder()
            .title("제목")
            .content("내용")
            .build();

    postRepository.save(post);

    mockMvc.perform(get("/posts/{id}", post.getId())
            .contentType(APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.title").value("제목"))
            .andExpect(jsonPath("$.content").value("내용"))
            .andDo(print());
}
@Test
@DisplayName("/posts/{id} 게시글 수정")
void update() throws Exception {
    Post post = Post.builder()
            .title("제목")
            .content("내용")
            .build();

    postRepository.save(post);

    UpdatePostDto updatePostDto = UpdatePostDto.builder()
            .title("제목수정")
            .content("내용수정")
            .build();

    mockMvc.perform(patch("/posts/{id}", post.getId())
            .contentType(APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(updatePostDto)))
            .andExpect(status().isOk())
            .andDo(print());

}
@Test
@DisplayName("/posts/{postId} 게시글 삭제")
void deleteTest() throws Exception {
    Post post = Post.builder()
            .title("제목")
            .content("내용")
            .build();

    postRepository.save(post);

    mockMvc.perform(delete("/posts/{id}", post.getId()))
            .andExpect(status().isOk())
            .andDo(print());
}

728x90

댓글