批量运行单元测试时出现Failed to load ApplicationContext异常
PostgreSQL连接槽耗尽导致批量单元测试失败的解决办法
你遇到的核心问题是PostgreSQL数据库可用连接槽被耗尽。单独运行单个测试时,仅启动一个Spring上下文,占用的连接数远低于数据库上限;但执行mvn test批量运行时,多个测试类可能重复初始化Spring容器,每个容器都会创建独立的数据库连接池,短时间内占满所有普通用户连接槽,最终抛出连接失败异常。
异常核心信息:
java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution Caused by: org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections
解决办法
- 复用Spring测试上下文:确保所有测试类使用相同的配置类(比如统一用
@SpringBootTest指定启动类),Spring会自动根据配置的哈希值复用已创建的上下文,避免重复初始化连接池。 - 缩小测试环境连接池规模:在
application-test.yml中降低连接池最大连接数,例如:
减少单个上下文占用的连接资源。spring: datasource: hikari: maximum-pool-size: 5 - 按需清理上下文:仅在测试修改了上下文状态时,给测试类添加
@DirtiesContext注解,确保测试结束后关闭上下文并释放连接,避免无效连接占用资源。 - 调整PostgreSQL连接上限:修改PostgreSQL配置文件
postgresql.conf,增大max_connections值(比如设为100),重启数据库生效。注意该值受系统内存限制,不要设置过大。 - 改用嵌入式数据库:对于无需真实数据库的单元测试,使用H2等嵌入式数据库,彻底避免占用PostgreSQL连接资源。
内容的提问来源于stack exchange,提问作者Laura
相关产品推荐
相关产品推荐

