[스프링빈] Junit5 환경에서 테스트 진행중 @EnableJpaAuditing 오류
2023. 9. 2. 23:06ㆍspring
[문제발생]
주요 오류는 다음과 같다.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaAuditingHandler': Cannot resolve reference to bean 'jpaMappingContext' while setting constructor argument
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': JPA metamodel must not be empty
Caused by: java.lang.IllegalArgumentException: JPA metamodel must not be empty
JPA metamodel must not be empty.
JPA 메타 모델은 비울 수 가 없다고 한다.
그 위에도 jpaMappingContext, jpaAuditingHandler.
@EnableJpaAuditing 때문에 발생한 오류임을 유추할 수 있다.
[원인]
그렇다면 왜 ?
@Configuration
@Profile({"dev", "test"})
@Transactional
public class NotProd {
@Bean
CommandLineRunner initData(
처음에는 요놈 때문이라고 생각했다.
초기 실행시 CommandLineRunner 를 통해 데이터를 생성하기 위해 Jpa를 사용한다고 생각했다.
하지만 해당 클래스를 주석처리 해도 마찬가지였다.
그리고 unit 테스트로 구현했기 때문에 ActiveProfile("test") 를 명시하지 않았다.
그래서 해당 오류가 발생한 ControllerTest 를 곰곰히 생각해보니 WebMvcTest를 사용했다.
@WebMvcTest(MemberController.class)
@Import({
SecurityConfig.class,
JwtAuthorizationFilter.class,
JwtTokenProvider.class}
)
@Slf4j
class MemberControllerTest
@WebMvcTest 는 아래와 같이 컨트롤러 테스트에 필요한 몇 개의 컴포넌트 외에는 컴포넌트를 스캔하지 않는다.
- @Controller
- @ControllerAdvice
- @JsonComponent
- Converter/GenericConverter
- Filter
- WebMvcConfigurer
- HandlerMethodArgumentResolver
즉, @Component, @Service, @Repository beans는 포함하지 않는다.
따라서 Jpa관련 Bean을 스캔하지 않는데 불구하고 SpringBootApplication에 @EnableJpaAuditing 어노테이션을 사용했기 때문에 발생하는 오류이다.
[문제해결]
@EnableJpaAuditing을 사용하기 위한 Configuration을 따로 분리해준다.
@Configuration
@EnableJpaAuditing
public class JpaAuditingConfig {
}
또는 테스트 코드 클래스단에 아래와 같이 추가해준다.
@MockBean(JpaMetamodelMappingContext.class)
'spring' 카테고리의 다른 글
[리팩토링] ILikeYou 프로젝트 스프링 이벤트, pub/sub구조 적용 (의존성 줄이기) (0) | 2023.08.02 |
---|---|
[SpringBoot] GET, POST 이외의 HTTP 메서드 사용하기 위한 설정 (0) | 2023.05.05 |
[SpringBoot] @ToString(callSuper = true) (0) | 2023.04.13 |
[SpringBoot] 글 삭제했을 때 원래 페이지로 redirect 되게 하기 (0) | 2023.03.31 |
[SpringBoot] 하나의 form을 재활용 하기 위한 방법 (ex_등록,수정을 하나의 form으로 <csrf>) (0) | 2023.03.31 |