OPEN HYPER STEP
← 목록으로 (Java+Spring)
JAVA · 82 / 99
java
CHAPTER 82 / 99
읽기 약 2
FUNCTION

통합 테스트: @SpringBootTest


핵심 개념

@SpringBootTest·@AutoConfigureMockMvc·TestRestTemplate — API 엔드포인트 통합 테스트.

본문

@SpringBootTest 기본

JAVA📋 코드 (42줄)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class UserControllerIntegrationTest {

    @Autowired MockMvc mockMvc;
    @Autowired ObjectMapper objectMapper;
    @Autowired UserRepository userRepository;

    @BeforeEach
    void setUp() {
        userRepository.deleteAll();
    }

    @Test
    void signup_returns_201() throws Exception {
        SignupRequest req = new SignupRequest(
            "alice@example.com", "Pass1234", "Alice"
        );

        mockMvc.perform(post("/api/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
            .andExpect(status().isCreated())
            .andExpect(jsonPath("$.email").value("alice@example.com"))
            .andExpect(jsonPath("$.name").value("Alice"))
            .andDo(print());
    }

    @Test
    void signup_invalid_email_returns_400() throws Exception {
        SignupRequest req = new SignupRequest(
            "invalid-email", "Pass1234", "Alice"
        );

        mockMvc.perform(post("/api/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.errors.email").exists());
    }
}

H2 인메모리 DB — application-test.yml

YAML📋 코드 (10줄)
spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    username: sa
    password:
  jpa:
    hibernate:
      ddl-auto: create-drop
    show-sql: true

TestRestTemplate — 실제 HTTP 호출

JAVA📋 코드 (28줄)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
class UserApiE2ETest {

    @Autowired TestRestTemplate restTemplate;
    @LocalServerPort int port;

    @Test
    void full_signup_flow() {
        SignupRequest req = new SignupRequest(
            "alice@example.com", "Pass1234", "Alice"
        );

        ResponseEntity<UserDto> response = restTemplate.postForEntity(
            "/api/users", req, UserDto.class
        );

        assertEquals(HttpStatus.CREATED, response.getStatusCode());
        assertEquals("alice@example.com", response.getBody().email());

        // 후속 — 등록된 사용자 조회
        ResponseEntity<UserDto> get = restTemplate.getForEntity(
            "/api/users/" + response.getBody().id(),
            UserDto.class
        );
        assertEquals(HttpStatus.OK, get.getStatusCode());
    }
}

@WebMvcTest — 컨트롤러만

JAVA📋 코드 (33줄)
@WebMvcTest(UserController.class)
class UserControllerTest {

    @Autowired MockMvc mockMvc;
    @MockBean UserService userService;
    @Autowired ObjectMapper objectMapper;

    @Test
    void getUser_returns_200() throws Exception {
        UserDto dto = new UserDto(1L, "alice@example.com", "Alice", "USER", LocalDateTime.now());
        when(userService.findById(1L)).thenReturn(dto);

        mockMvc.perform(get("/api/users/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.email").value("alice@example.com"));
    }
}


// @DataJpaTest — Repository만
@DataJpaTest
class UserRepositoryTest {
    @Autowired UserRepository userRepository;

    @Test
    void findByEmail_returns_user() {
        User user = User.builder().email("alice@example.com").build();
        userRepository.save(user);

        Optional<User> found = userRepository.findByEmail("alice@example.com");
        assertTrue(found.isPresent());
    }
}

다음 챕터

CH.14 "Testcontainers" — 실제 DB로 테스트.


AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude

무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6

내 Spring 코드의 통합 테스트 부분을 분석해서
테스트 슬라이스 적정성와 개선 우선순위를 알려줘.
ChatGPT

무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro

통합 테스트 vs 다른 패턴 비교를
실전 사례 5개로 보여주고 @SpringBootTest vs @WebMvcTest를 알려줘.
Gemini

무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro

내 코드베이스 전체를 분석해서
통합 테스트 관련 느린 테스트·flaky 위치를 보고해줘.
Grok

무료: Grok 4.1 / SuperGrok $30/mo

2026년 한국 기업의 통합 테스트 채택률과
한국 백엔드 통합 테스트 패턴를 솔직히 알려줘.

⭐ 이것만 기억하세요
통합 테스트: @SpringBootTest 이 3가지만 확실히 잡으세요
1.@SpringBootTest = 풀 컨텍스트, @WebMvcTest = 컨트롤러만, @DataJpaTest = Repository만
2.MockMvc로 컨트롤러 테스트 + TestRestTemplate으로 실제 HTTP — 단계별 격리
3.다음 챕터 CH.14에서 Testcontainers — 실제 PostgreSQL로 테스트


공유하기
진행도 82 / 99