gpt4 book ai didi

java - Spring 测试多次关闭嵌入式数据库

转载 作者:行者123 更新时间:2023-11-30 06:14:08 25 4
gpt4 key购买 nike

我正在使用这样定义的 h2 嵌入式数据库:

<jdbc:embedded-database id="embeddedDatasource" type="h2"/>

我有两个测试:

@RunWith(SpringJunit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:h2-context.xml")
class Test1 {...}

@RunWith(SpringJunit4ClassRunner.class)
@ContextConfiguration("classpath:h2-context.xml")
class Test2 {...}

在执行所有测试后,我确实在日志中看到了:

* Closing org.springframework.context.support.GenericApplicationContext
* Closing org.springframework.web.context.support.GenericWebApplicationContext
* Closing JPA EntitiManagerFactory for Persistance unit ...
* Closing JPA EntitiManagerFactory for Persistance unit ...

因此,在所有测试执行后,每个上下文的实体管理器都会关闭。我知道 spring 缓存上下文文件,所以我猜 h2 bean 在两个测试之间共享。

问题是:有时我会遇到奇怪的异常,例如:

H2EmbeddedDatabaseConfigurer: Could not shutdown embedded database
jrg.h2.jdbc.JDBCSQLException: The database has been closed [90098-179]

我该如何解决?

这是我目前发现的: Spring’s embedded H2 datasource and DB_CLOSE_ON_EXIT

最佳答案

由于您使用的是 Spring Framework 3.1.4,您可能会看到 Spring 和 H2 之间的冲突结果都试图关闭数据库。

此冲突已在 Spring Framework 4.0.3 中得到解决(有关详细信息,请参阅 SPR-11573)。

具体来说,从 Spring 4.0.3 开始,嵌入式 H2 数据库是使用连接 URL 创建的:"jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false"。 “%s”是数据库的名称(例如,“testdb”)。

因此,如果您希望嵌入式 H2 数据库在 4.0.3 之前的 Spring 版本上具有相同的行为,您将需要使用类似于以下内容的连接 URL 手动创建 DataSource以上。

So, the entity manager is closed for each context after all tests execution. I know that spring caches context files, so I guess h2 bean is shared across two tests.

是的,Spring TestContext Framework 跨测试和测试类缓存 ApplicationContext。但是...嵌入式 H2 数据库的 DataSource 在这些上下文中共享。相反,在您上面概述的场景中,您最终会得到 2 个 DataSource - 每个上下文中都有一个,并且都引用同一个内存数据库。

Sooo,现在我想到了,您遇到的问题更有可能是因为您的两个 ApplicationContext 都试图关闭完全相同的内存数据库。要解决该问题,您可以考虑在每次创建嵌入式数据库时为其定义一个唯一的名称。有关此主题的详细信息,请阅读以下 JIRA 问题,这些问题已针对 Spring 4.2 解决,但仍包含有关如何在 4.2 之前实现相同目标的提示。

问候,

山姆

关于java - Spring 测试多次关闭嵌入式数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30806153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com