尽管'DB_CLOSE_ON_EXIT = FALSE',H2内存中测试数据库仍关闭

Ben*_*rer 4 java junit spring h2 spring-boot

我有一些简短的单元测试,但失败了:

javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
::
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
::
Caused by: org.h2.jdbc.JdbcSQLException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-197]
Run Code Online (Sandbox Code Playgroud)

来源是我的Spring Data AuditProvider,特别是以下行:

user = entityManager.createNamedQuery("findUserByUsernameAndTenant", User.class)
        .setParameter("tenant", TenantService.DEFAULT_TENANT_ID)
        .setParameter("username", UserService.USER_SYSTEM).getSingleResult();
Run Code Online (Sandbox Code Playgroud)

在执行整个测试套件时才发生错误,而在运行此测试类时才发生。

这是我正在使用的TestRunner等:

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@Rollback
public class MyTest {
Run Code Online (Sandbox Code Playgroud)

那是我的数据源URL:

spring.datasource.url: 'jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE'
Run Code Online (Sandbox Code Playgroud)

因此,看来“ DB_CLOSE_ON_EXIT”不能解决问题,知道这是怎么回事吗?

更新:

我刚刚意识到,只有在Eclipse中运行测试时才会发生这种情况,但是它们是在命令行中运行的。虽然我偶尔会得到:

o.s.b.f.support.DisposableBeanAdapter    : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL)
Run Code Online (Sandbox Code Playgroud)

但我没有得到PersistenceException和stacktrace。

Oli*_*ire 5

DB_CLOSE_DELAY仅使用。

对于内存数据库,您不应使用DB_CLOSE_ON_EXIT=FALSE:您只能使用DB_CLOSE_DELAY=-1。请参阅http://www.h2database.com/html/features.html#in_memory_databases

因此,您的数据源应为:

spring.datasource.url: 'jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1'
Run Code Online (Sandbox Code Playgroud)

您的单元测试也有可能在并行过程中执行。确保它们都在同一VM中运行。

如果使用Maven,请设置forkCount0

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.22.0</version>
  <configuration>
    <forkCount>0</forkCount>
  </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

  • @OlivierGrégoire,您不应该使用“DB_CLOSE_ON_EXIT=FALSE”,请参阅[文档](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql) .html#boot-features-embedded-database-support) - _如果出于某种原因,您确实为嵌入式数据库配置了连接 U​​RL,请注意确保禁用数据库的自动关闭功能。_ (2认同)