티스토리 뷰
728x90
반응형
@SpringBootTest
- Spring Boot 프로젝트에서 통합 테스트를 위해 사용되는 애노테이션
- Spring 컨텍스트를 확장하고 Spring Boot 애플리케이션의 전체 설정을 로드하여 테스트 환경을 구성
- 내장 웹 서버를 사용하여 테스트를 실행
@SpringBootTest // Spring Boot 통합 테스트 설정
public class MyIntegrationTest {
@Autowired
private MyService myService;
@Test
public void testSomething() {
// myService를 사용한 테스트 작성
}
}
- SpringBootContextLoader 기본 사용: @ContextConfiguration(loader=...)이 특별히 정의되지 않은 경우, @SpringBootTest는 기본적으로 SpringBootContextLoader를 사용하여 컨텍스트를 로드합니다.
- @SpringBootConfiguration 자동 검색: 중첩된 @Configuration이 사용되지 않고 명시적인 클래스가 지정되지 않은 경우, @SpringBootTest는 자동으로 @SpringBootConfiguration을 검색합니다.
- 속성(properties) 및 인자(args) 설정 가능: properties 속성을 사용하여 사용자 정의 환경 속성을 정의할 수 있고, args 속성을 사용하여 애플리케이션 실행 시 사용할 인자를 정의할 수 있습니다.
- 다양한 웹 환경 모드 지원: 웹 환경의 다양한 모드를 지원하며, 정의된 또는 무작위 포트에서 동작하는 완전히 실행 중인 웹 서버를 시작할 수 있습니다.
- TestRestTemplate 및 WebTestClient 지원: 테스트 중에 완전히 실행 중인 웹 서버를 사용하는 웹 테스트에 대한 TestRestTemplate 및/또는 WebTestClient 빈을 등록합니다.
@AutoConfigureMockMvc
- Spring Boot 테스트에서 웹 계층의 테스트를 위해 MockMvc를 설정하고 주입하는 역할
- 실제 웹 서버를 띄우지 않고도 컨트롤러를 테스트
- @AutoConfigureMockMvc는 @WebMvcTest와 다르게 컨트롤러만이 아닌 다양한 빈들도 로드되므로, 보다 통합적인 테스트 시나리오에서 사용
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testSayHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Hello, World!"));
}
}
@MockBean
- Spring Boot 테스트에서 사용되며, 실제 Spring ApplicationContext에 빈으로 등록되는 목(mock) 객체를 생성
- Spring Boot 애플리케이션 컨텍스트 내에서만 작동하며, 실제 빈과 교체
- @Mock은 순수한 Mockito 목(mock)을 생성하는 데 사용되고 Spring과 관련이 없음
@SpringBootTest
public class MyServiceIntegrationTest {
@Autowired
private MyService myService; // 실제 빈 주입
@MockBean
private MyRepository myRepository; // 목(mock) 빈 주입
@Test
public void testMyService() {
// MyRepository의 메서드를 목(mock) 객체로 설정
when(myRepository.getData()).thenReturn("Mocked Data");
// MyService는 실제 빈이지만 MyRepository는 목(mock) 객체를 사용
String result = myService.processData();
// 검증
// MyService가 MyRepository의 목(mock)을 호출하여 목(mock)이 설정한 값을 반환하는지 확인
assertEquals("Processed Mocked Data", result);
}
}
@SpyBean
- @SpyBean은 기존 기능을 유지하면서 부분적인 검증이나 특정 메서드 스터빙이 필요한 경우 유용합니다.
- Spring Boot 기반의 통합 테스트에서 실제 로직 일부를 확인하거나 디버깅하고 싶을 때 적합합니다.
- 스프링 컨텍스트에 등록된 빈을 스파이로 교체
- 기존 빈의 기능을 유지하면서, 특정 동작만 감시하거나 변경 가능.
- 새로운 스파이 빈 생성
- 주입할 빈이 없으면 새 스파이 객체를 생성하여 사용.
- Mockito의 spy()와 통합
- Mockito의 spy() 메서드를 활용하지만, Spring Application Context와 자연스럽게 통합.
기존 빈을 스파이로 감싸기
@SpringBootTest
class MyServiceTest {
@SpyBean
private MyService myService; // 기존 MyService 빈을 스파이로 감쌈
@Test
void testSpyBean() {
// 실제 메서드 호출
String result = myService.someMethod();
// 특정 메서드 스터빙
doReturn("stubbed result").when(myService).someMethod();
assertEquals("stubbed result", myService.someMethod());
}
}
새로운 스파이 빈 생성
@SpringBootTest
class MyServiceTest {
@SpyBean
private MyService myService; // 컨텍스트에 없는 경우 새로 생성
@Test
void testSpyBeanWithNewBean() {
assertNotNull(myService);
}
}
다른 빈과의 상호작용 감시
@SpringBootTest
class MyControllerTest {
@SpyBean
private MyService myService;
@Autowired
private MyController myController;
@Test
void testControllerCallsService() {
myController.handleRequest();
// MyService의 메서드 호출 여부 검증
verify(myService).performAction();
}
}
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing
728x90
반응형
'Spring' 카테고리의 다른 글
[Spring Boot] OpenFeign 로깅 설정 (0) | 2023.10.01 |
---|---|
[Spring Boot] OpenFeign (0) | 2023.09.28 |
[Spring] MockMvc 사용 시 403 Forbidden 에러 발생 (0) | 2023.08.27 |
[Spring] @WebMvcTest MockMvc 테스트 (0) | 2023.08.27 |
[Spring Boot] MyBatis 쿼리 log4j 로그 출력 설정 (0) | 2023.08.15 |
반응형
300x250