현재 진행하고 있는 `Study With Me` 프로젝트에서 `@MockBean`을 사용하려고 보니

deprecated 되었다..
그럼 뭘로 대체 되었을까 찾아보았는데
`@MockitoBean`으로 대체되었음을 확인했다.
사용 방법은 아래처럼 똑같이 사용하면 된다.
@MockitoBean
private StudyRoomCommandService commandService;
아래는 이곳저곳에서 deprecated 된다는 흔적이다.
https://github.com/spring-projects/spring-boot/issues/41157
Make @MockBean respect @Qualifier when replacing beans in application context · Issue #41157 · spring-projects/spring-boot
In our application, we have several JmsTemplate beans. The @MockBean is intended to replace or create a bean in the application context with the matching type. In current implementation, we cannot ...
github.com
MockBean
Deprecated (for removal) Annotation that can be used to add mocks to a Spring ApplicationContext. Can be used as a class level annotation or on fields in either @Configuration classes, or test classes that are @RunWith the SpringRunner. Mocks can be regist
docs.spring.io
그리고 Spring 공식문서에서 설명하는 `@MociktoBean`의 설명은 다음과 같다.
`@MockitoBean`의 역할
- 테스트 환경에서 애플리케이션 컨텍스트(ApplicationContext)의 빈을 모킹하도록 설정
- 주로 `Mockito` 라이브러리와 함께 사용되며, 테스트 시 특정 빈의 동작을 가짜로 대체하고자 할 때 유용
- `@MockBean`과 거의 동일
`@MockitoBean` 사용 대상
- 이 어노테이션은 테스트 클래스의 필드에만 적용 가능
- 모킹할 빈은 필드의 타입에서 자동으로 추론되며, 해당 빈이 테스트 컨텍스트에 오버라이드(교체) 된다.
디테일
- 어노테이션이 적용된 필드의 타입에 따라 모킹할 빈이 자동으로 선택
- 빈이 여러개 있는 경우
- `@Qualifier`를 사용해 명시적으로 선택
- 필드 이름이 빈 이름으로 사용되어 자동 매칭 시도
- 빈이 존재하지 않는 경우
- 빈이 컨텍스트에 없는 경우, 해당 빈이 새롭게 생성되고 모킹
- 그러나, 빈이 반드시 존재해야 한다면 `enforceOverride = true` 설정
- 이 경우 빈이 없다면 테스트 실패
'Spring > Test' 카테고리의 다른 글
| [테스트 코드] 스프링에서의 Redis 테스트 환경 구축 (0) | 2024.11.29 |
|---|---|
| [테스트 코드] @DataJpaTest 사용 (0) | 2024.11.24 |
| [테스트 코드] 테스트 코드에서 static method를 사용하는 법 (0) | 2024.11.24 |
| [테스트 코드] 단위 테스트 @InjectMock 사용방법 (0) | 2024.11.24 |
| [테스트 코드] 테스트 코드 이해하기 (0) | 2024.11.22 |