spring

@WebMvcTest IllegalArgumentException: JPA metamodel must not be empty 오류 뜰때

seungmin576 2025. 3. 6. 22:02

방법 1: Configuration 설정 분리

@EnableJpaAuditing 설정을 별도의 Configuration 클래스로 분리하여 테스트 시 JPA 관련 빈들이 로드되지 않도록 합니다. 예를 들어:

java
@Configuration
@EnableJpaAuditing
public class JpaConfig {
}

이렇게 하면 테스트 코드 실행 시 Application이 JPA와 상관없이 정상 실행하게 됩니다.

방법 2: MockBean 추가

테스트 코드에 JpaMetamodelMappingContext 클래스를 @MockBean으로 추가합니다. 예를 들어:

java
@WebMvcTest(StoreController.class)
public class StoreControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private StoreService storeService;

    @MockBean
    private JwtUtil jwtUtil;

    @MockBean
    private JpaMetamodelMappingContext jpaMetamodelMappingContext;

    @Test
    void shouldFindStoreById() throws{
    
    }

 

JpaMetamodelMappingContext

는 JPA 메타모델을 관리하는 컨텍스트입니다.

이 클래스는 JPA 엔티티와 메타모델 클래스 간의 매핑 정보를 유지하는 데 사용됩니다.

Spring Boot는 JPA를 사용할 때 이러한 메타모델 정보를 필요로 합니다.

 

@WebMvcTest 어노테이션은 주로 컨트롤러 레이어만 테스트하기 위해 사용됩니다.

이 테스트는 데이터베이스나 서비스 레이어를 실제로 로드하지 않고, 최소한의 웹 컨텍스트를 생성하여 빠르게 테스트를 실행할 수 있습니다. 그러나, JPA와 관련된 의존성이 없기 때문에, JPA 메타모델을 인식하지 못해 IllegalArgumentException: JPA metamodel must not be empty 오류가 발생하게 됩니다.

@MockBean JpaMetamodelMappingContext를 추가하면, Spring이 JPA 메타모델 정보를 필요로 할 때, 실제 메타모델 대신 모킹된 빈을 사용하게 되어 오류를 회피할 수 있습니다.

이를 통해 다음과 같은 문제를 해결할 수 있습니다:

  1. JPA 메타모델 부재: @WebMvcTest는 JPA 엔티티 및 메타모델 빈을 로드하지 않으므로, 메타모델이 비어 있는 상태가 됩니다.
  2. Mocking: JpaMetamodelMappingContext를 모킹하여 JPA 메타모델의 부재로 인한 예외를 피할 수 있습니다.

따라서, JpaMetamodelMappingContext를 @MockBean으로 추가하면 Spring Boot가 이 클래스에 대한 의존성을 해결할 수 있게 되어 문제를 해결할 수 있습니다.