You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.2.0中JUnit测试无法加载ApplicationContext问题求助

问题描述

有一段JUnit测试代码在Spring Boot 3.1版本运行正常,升级到3.2.0后出现无法加载ApplicationContext的错误。

测试代码如下:

@ExtendWith(SpringExtension.class)
@DataJpaTest
@Import(TestCreateService.class)
public class CreateServiceTest{
  @Autowired private TestCreateService testCreateService;
  @Autowired private TestRepository testRepository;

   ...

  @Test
  public void bulkGetOrCreateTest() throws InterruptedException {
       ...
      assertThat(executorService.awaitTermination(60, TimeUnit.SECONDS)).isTrue();
      assertThat(testRepository.count()).isEqualTo(1);
    }
  }

}

简化后的报错信息:

java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@58a63629 testClass = com.example.helloworld.repository.UserRepositoryTest, locations = [], classes = [com.example.helloworld.HelloWorldApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceDescriptors = [], propertySourceProperties = ["org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true"], contextCustomizers = [[ImportsContextCustomizer@7de843ef key = [org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration, org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcClientAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@302c971f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@35841320, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@71075444, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@34be3d80, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@884bb438, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizer@4d15107f, org.springframework.boot.test.context.SpringBootTestAnnotation@cd76d185], contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:180)
    ...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testEntityManager' defined in class path resource [org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerAutoConfiguration.class]: Unsatisfied dependency expressed through method 'testEntityManager' parameter 0: No qualifying bean of type 'jakarta.persistence.EntityManagerFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    ...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'jakarta.persistence.EntityManagerFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    ...

疑问:Spring Boot 3.2.0有哪些相关变更?Repository层JUnit测试的写法是否发生了改变?


问题分析与解决方案

Spring Boot 3.2.0相关变更(与该问题直接相关)

  • JPA自动配置拆分:3.2版本将原HibernateJpaAutoConfiguration的职责拆分,其中EntityManagerFactory的自动配置被独立到新的EntityManagerFactoryAutoConfiguration类中,原配置类不再负责这部分逻辑。
  • 测试切片自动配置调整:@DataJpaTest的默认自动配置集合有所缩减,部分之前默认加载的配置类现在需要显式导入才能生效。

Repository层JUnit测试写法调整方案

针对报错中找不到EntityManagerFactory的问题,可通过以下方式修复:

  1. 显式导入缺失的自动配置类
    在测试类上添加EntityManagerFactoryAutoConfiguration的导入,补足上下文所需的Bean:
@DataJpaTest
@Import({TestCreateService.class, EntityManagerFactoryAutoConfiguration.class})
public class CreateServiceTest{
  // 原有测试代码不变
}
  1. 简化测试注解
    Spring Boot 3.2中@DataJpaTest已默认集成@ExtendWith(SpringExtension.class),可以直接移除该注解,精简代码:
@DataJpaTest
@Import({TestCreateService.class, EntityManagerFactoryAutoConfiguration.class})
public class CreateServiceTest{
  // 原有测试代码不变
}
  1. 确认测试数据库配置
    如果测试依赖嵌入式数据库,可显式指定数据库替换策略,避免自动配置拆分导致的数据源初始化异常:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import({TestCreateService.class, EntityManagerFactoryAutoConfiguration.class})
public class CreateServiceTest{
  // 原有测试代码不变
}
  1. 统一依赖版本
    确保项目中spring-boot-starter-data-jpa和spring-boot-starter-test的版本均为3.2.0,避免依赖冲突导致自动配置失效。

内容的提问来源于stack exchange,提问作者francissoria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 06:17:28