@SpringBootTest@AutoConfigureMockMvc// MockMvc 자동 설정@Transactional// 각 테스트 후 DB 롤백classPostApiIntegrationTest{@AutowiredprivateMockMvc mockMvc;@AutowiredprivatePostRepository postRepository;@BeforeEachvoidsetUp(){ postRepository.deleteAll();// 매 테스트 전 DB 초기화}@Test@DisplayName("게시글을 생성하면 DB에 저장된다")voidcreatePost_savedToDatabase()throwsException{// GivenString requestBody ="""
{"title": "제목", "content": "내용"}
""";// When mockMvc.perform(post("/api/posts").contentType(MediaType.APPLICATION_JSON).content(requestBody)).andExpect(status().isCreated());// ThenassertThat(postRepository.findAll()).hasSize(1);}}
@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.MOCK)// 기본값 — MockMvc@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.RANDOM_PORT)// 실제 서버, 랜덤 포트@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.DEFINED_PORT)// 실제 서버, 고정 포트@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.NONE)// 웹 환경 없음
# application-test.yml (test 환경 전용 설정)spring:datasource:url: jdbc:h2:mem:testdb # 인메모리 H2 DB 사용jpa:hibernate:ddl-auto: create-drop # 테스트 시 스키마 자동 생성/제거