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。
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,请设置forkCount为0:
<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)
| 归档时间: |
|
| 查看次数: |
4787 次 |
| 最近记录: |