Data REST API Test

zhzkzhffk·2022년 11월 30일
0

스프링 테스트

목록 보기
2/5
post-thumbnail

Data REST API Test Code 작성
슬라이스 테스트에서는 작동을 못한다. 이에 따라 통합 테스트로 진행한다.

@WebMvcTest (문제 상황)

import org.springframework.test.web.servlet.MockMvc;

@DisplayName("DATA REST API 테스트")
@WebMvcTest
public class DataRestTest {
	private final MockMvc mvc;
    
    public DataRestTest(@Autowired MockMvc mvc) {
        this.mvc = mvc;
    }
    
    @DisplayName("[api] 게시글 리스트 조회")
    @Test
    void givenNothing_whenRequestingArticle_thenReturnsArticlesJsonResponse() throws Exception {
        // when & then
        mvc.perform(get("/api/articles"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.valueOf("application/hal+json")))
                .andDo(print());
    }
}
  • 위의 테스트는 API가 존재하지만 200번이 아닌 404번의 오류가 발생한다.
    • @WebMvcTest는 Slice Test 이므로 Controller외의 Bean들을 로드하지 않는다.
    • 따라서 Data Rest Auto Configuration을 읽지 않은 것이다.
    • Configuration 공식 문서

문제 해결


@AutoConfigureMockMvc, @SpringBootTest


@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class DataRestTest {

    private final MockMvc mvc;

    public DataRestTest(@Autowired MockMvc mvc) {
        this.mvc = mvc;
    }

    @DisplayName("[api] 게시글 리스트 조회")
    @Test
    void givenNothing_whenRequestingArticle_thenReturnsArticlesJsonResponse() throws Exception {
        // when & then
        mvc.perform(get("/api/articles"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.valueOf("application/hal+json")))
                .andDo(print());
        // import 안 나올 때 ctrl + space, static 으로 가져올 때는 option + enter
    }
  • @SpringBootTest
    • webEnvironment = SpringBootTest.WebEnvironment.MOCK (default): 이 때 내장톰캣을 구동하지 않아 서블릿이 아니라 서블릿을 Mocking한 컨테이너가 뜬다.
    • 참고 하면 좋은 블로그
    • 통합 테스트: API를 실행하면서 DB에 영향을 준다. 이에 따라 Test Class 위에 @Transactional을 붙혀 기본적인 방식인 Rollback이 작동하게 만든다.

@Transactional 추가 (문제 해결)


@AutoConfigureMockMvc
@Transactional
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class DataRestTest {

    private final MockMvc mvc;

    public DataRestTest(@Autowired MockMvc mvc) {
        this.mvc = mvc;
    }

    @DisplayName("[api] 게시글 리스트 조회")
    @Test
    void givenNothing_whenRequestingArticle_thenReturnsArticlesJsonResponse() throws Exception {
        // when & then
        mvc.perform(get("/api/articles"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.valueOf("application/hal+json")))
                .andDo(print());
        // import 안 나올 때 ctrl + space, static 으로 가져올 때는 option + enter
    }
profile
Backend Developer

0개의 댓글