用于测试的嵌入式 H2 数据库的 Spring 配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2012292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:57:58  来源:igfitidea点击:

Spring configuration for embedded H2 database for tests

unit-testingspringembedded-databaseh2

提问by Hans-Peter St?rr

What does your Spring configuration for integration tests look like using an embedded h2 datasourceand, optionally, JUnit?

使用嵌入式 h2 数据源和可选的 JUnit进行集成测试的 Spring 配置是什么样的?

My first try with a SingleConnectionDataSourcebasically 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 modemight work as well, but this is probably not the fastest communication mode for a temporary embedded database in memory.

我第一次尝试使用SingleConnectionDataSource基本上是有效的,但在更复杂的测试中失败了,因为你需要同时连接多个连接或挂起事务。我认为基于 tcp 的服务器模式下的h2也可能工作,但这可能不是内存中临时嵌入式数据库的最快通信模式。

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.

更新:让我们指定一些对此类测试很重要的具体要求。

  • The database should be temporary and in memory
  • The connection should probably not use tcp, for speed requirements
  • It would be nice if I could use a database tool to inspect the content of the database during debugging
  • We have to define a datasource since we can't use the application servers datasource in unit tests
  • 数据库应该是临时的并且在内存中
  • 为了速度要求,连接可能不应该使用 tcp
  • 如果我可以在调试期间使用数据库工具检查数据库的内容,那就太好了
  • 我们必须定义一个数据源,因为我们不能在单元测试中使用应用程序服务器数据源

回答by matsev

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.

保留不知道有没有什么工具可以检查数据库,我认为一个简单的解决方案是使用支持HSQL、H2和Derby的Spring嵌入式数据库(3.1.x docscurrent docs) .

Using H2, your xml configuration would look like the following:

使用 H2,您的 xml 配置将如下所示:

<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>

If you prefer Java based configuration, you can instantiate a DataSourcelike this (note that EmbeddedDataBaseextends DataSource):

如果你更喜欢基于 Java 的配置,你可以DataSource像这样实例化一个(注意EmbeddedDataBaseextends DataSource):

@Bean(destroyMethod = "shutdown")
public EmbeddedDatabase dataSource() {
    return new EmbeddedDatabaseBuilder().
            setType(EmbeddedDatabaseType.H2).
            addScript("db-schema.sql").
            addScript("db-test-data.sql").
            build();
}

The database tables are created by the db-schema.sqlscript and they are populated with test data from the db-test-data.sqlscript.

数据库表由db-schema.sql脚本创建,并用来自db-test-data.sql脚本的测试数据填充。

Don't forget to add the H2 database driver to your classpath.

不要忘记将 H2 数据库驱动程序添加到您的类路径中。

回答by Hans-Peter St?rr

I currently include in a test-only springconfig-file as a datasource:

我目前包含在一个仅用于测试的 springconfig 文件中作为数据源:

<bean id="database.dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
    <constructor-arg>
        <bean class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
            <property name="driverClass" value="org.h2.Driver" />
            <property name="url"
                value="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=Oracle;TRACE_LEVEL_SYSTEM_OUT=2" />
        </bean>
    </constructor-arg>
</bean>

<!-- provides a H2 console to look into the db if necessary -->
<bean id="org.h2.tools.Server-WebServer" class="org.h2.tools.Server" 
    factory-method="createWebServer" depends-on="database.dataSource" 
    init-method="start" lazy-init="false">
    <constructor-arg value="-web,-webPort,11111" />
</bean>

Creating / dropping the tables can be done by using executeSqlScript when overriding AbstractAnnotationAwareTransactionalTests.onSetUpBeforeTransaction, or with SimpleJdbcTestUtils.executeSqlScriptin an appropriate place.

创建/删除表可以通过在覆盖AbstractAnnotationAwareTransactionalTests.onSetUpBeforeTransaction时使用 executeSqlScript或在适当的位置使用SimpleJdbcTestUtils.executeSqlScript来完成。

Compare also this posting.

也比较这个帖子

回答by ejboy

H2 is bundled with a built-in connection pool implementation. The following XML provides an example of using it as a Datasource bean without a need to introduce additional dependencies on DBCP or C3P0:

H2 与内置连接池实现捆绑在一起。以下 XML 提供了将其用作数据源 bean 的示例,而无需引入对 DBCP 或 C3P0 的其他依赖项:

<bean id="dataSource" class="org.h2.jdbcx.JdbcConnectionPool" destroy-method="dispose">
    <constructor-arg>
        <bean class="org.h2.jdbcx.JdbcDataSource">
            <property name="URL" value="jdbc:h2:dbname"/>
            <property name="user" value="user"/>
            <property name="password" value="password"/>
         </bean>
    </constructor-arg>
</bean> 

The database will be shut down by calling a dispose method when Spring application context closes.

当 Spring 应用程序上下文关闭时,将通过调用 dispose 方法关闭数据库。

回答by Bozho

I think it's best to use your production DataSource implementation (only with different connection-string) for the unit-tests.

我认为最好将您的生产数据源实现(仅使用不同的连接字符串)用于单元测试。

Anyway "failed on more complicated tests" doesn't give enough information for a more detailed answer.

无论如何,“在更复杂的测试中失败”并没有为更详细的答案提供足够的信息。

(Self-ad : check this)

(自我广告:检查这个