嵌入式H2数据库的Spring配置以进行测试 [英] Spring configuration for embedded H2 database for tests
问题描述
使用嵌入式h2数据源进行集成测试的Spring配置看起来像什么,并且,可以选择使用JUnit吗?
What does your Spring configuration for integration tests look like using an embedded h2 datasource and, optionally, JUnit?
我第一次尝试使用 SingleConnectionDataSource 基本上可以运行,但是在更复杂的测试中失败了,在该测试中您需要同时进行多个连接或暂停事务.我认为基于TCP的服务器模式中的h2 可能有效同样,但是对于内存中的临时嵌入式数据库,这可能不是最快的通信模式.
My first try with a SingleConnectionDataSource basically worked, but failed on more complicated tests where you need several connections at the same time or suspended transactions. I think h2 in tcp based server mode might work as well, but this is probably not the fastest communication mode for a temporary embedded database in memory.
有哪些可能性及其优势/劣势?另外,如何创建表/填充数据库?
What are the possibilities and their advantages / disadvantages? Also, how do you create the tables / populate the database?
更新:让我们指定一些对于此类测试很重要的具体要求.
Update: Let's specify some concrete requirements that are important for such tests.
- 数据库应该是临时的并且在内存中
- 出于速度要求,连接可能不应该使用tcp
- 如果能在调试过程中使用数据库工具检查数据库内容,那就太好了
- 我们必须定义一个数据源,因为我们不能在单元测试中使用应用服务器数据源
推荐答案
由于不知道是否有任何工具可以检查数据库,我认为一个简单的解决方案是使用Spring嵌入式数据库( 3.1.x docs ,当前文档),该文档支持HSQL,H2和Derby.
With the reservation that I do not know if there is any tool that can inspect the database, I think that a simple solution would be to use the Spring embedded database (3.1.x docs, current docs) which supports HSQL, H2, and Derby.
使用H2,您的xml配置如下所示:
Using H2, your xml configuration would look like the following:
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:db-schema.sql"/>
<jdbc:script location="classpath:db-test-data.sql"/>
</jdbc:embedded-database>
如果您喜欢基于Java的配置,则可以像这样实例化DataSource
(请注意,EmbeddedDataBase
扩展了DataSource
):
If you prefer Java based configuration, you can instantiate a DataSource
like this (note that EmbeddedDataBase
extends DataSource
):
@Bean(destroyMethod = "shutdown")
public EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder().
setType(EmbeddedDatabaseType.H2).
addScript("db-schema.sql").
addScript("db-test-data.sql").
build();
}
数据库表是由 db-schema.sql 脚本创建的,并由 db-test-data.sql 脚本中的测试数据填充.
The database tables are created by the db-schema.sql script and they are populated with test data from the db-test-data.sql script.
不要忘记将H2数据库驱动程序添加到您的类路径中.
Don't forget to add the H2 database driver to your classpath.
这篇关于嵌入式H2数据库的Spring配置以进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!