개발/java

SpringBoot API Test (DB)

엄호연 2022. 2. 21. 19:33

SpringBoot 에서 API 단위테스트를 작성하려고한다.

아주간단하게 아래와같이 테스트 대상클래스에 `@SpringBootTest`  어노테이션만 붙여주면된다.

 

@SpringBootTest
class FooTest {
    @Test
    @DisplayName("var를 반환한다.")
    void test1() throws Exception {
    }
}

 

 

API 테스트 + 실제 API 를 통한 데이터베이스 등록및 삭제 까지 진행하려면 `@AutoConfigureTestDatabase` 어노테이션을 추가해서 아래와같이 진행하면된다.

@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureTestDatabase
class FooTest {

    @Autowired
    private MockMvc mockMvc;
    
    @Autowired
    private FooRepository fooRepository;
    
    @Test
    @DisplayName("var를 반환한다.")
    void test1() throws Exception {
        mockMvc.perform(
                RestDocumentationRequestBuilders.
                        get("/api/v1/foo")
        ).andExpect(e -> {
            assertThat("var", is(e.getResponse().getContentAsString()));
        });
    }
}

gradle

  testImplementation 'com.h2database:h2:1.3.148'