java - 如何防止在Spring Boot单元测试中执行import.sql

标签 java spring hibernate

我的类路径中有一个 import.sql 文件,其中包含一些 INSERT 语句。当使用 profile=devel 运行我的应用程序时,它的数据正在加载到 postgres 数据库中,到目前为止一切正常。

当使用测试配置文件 import.sql 执行测试时,也会触发导入,这会导致“找不到表”异常。不确定这里的原因是什么,但无论如何我都不想使用该数据进行测试。

我怎样才能阻止它?为测试配置文件设置 hibernate.ddl-auto=none 似乎不是解决方案,因为它也阻止了架构的生成。

最佳答案

据我所知,您无法配置它。只要您使用create-dropcreate 模式,Hibernate 就会自动调用import.sql 文件。 the documentation也提到了这一点与 Spring 无关:

In addition, a file named import.sql in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the ddl-auto property is set to create or create-drop).

我的猜测是您仍然希望在测试场景中继续生成表格。在这种情况下,您可能希望通过在类路径中添加名为 schema.sqldata.sql 的文件来切换到 Spring boot 的数据源初始化。

此文件将在 Spring boot 启动时自动选取(仅适用于 Spring boot 2.0 中的嵌入式数据源),documentation 中也提到了这一点。 :

Spring Boot can automatically create the schema (DDL scripts) of your DataSource and initialize it (DML scripts). It loads SQL from the standard root classpath locations: schema.sql and data.sql, respectively.

现在,为了能够在测试阶段禁用加载数据,您可以使用配置文件。例如,对于 Spring boot 2.x,您可以使用以下属性禁用此功能:

spring.datasource.initialization-mode=never # Property for Spring boot 2.0
spring.datasource.initialize=false # Property for Spring boot 1.0

请注意,这会禁用架构创建和数据加载 SQL 文件。仅禁用 data.sql 文件是不可能的,但可以通过重命名 Spring boot 将查找的默认文件名来使用一个简单的技巧来实现:

spring.datasource.data=somethingelse.sql

如果您只在测试期间配置此属性,Spring boot 将查找名为 somethingelse.sql 的文件,而不会选择您的 data.sql 文件.当使用 dev 配置文件运行时,您丢弃此属性,Spring boot 将查找(并找到)data.sql


同时适用于 Spring boot 的 schema.sql/data.sql 和 Hibernate 的 import.sql 的替代方法是使用 Maven配置文件并在运行测试时加载不同的类路径文件夹。但是,我不建议这样做,因为它会使在 IDE 中运行测试变得更加困难。

关于java - 如何防止在Spring Boot单元测试中执行import.sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41188207/

相关文章:

javascript - 如何使用spring mvc接收数组作为参数?

java - hibernate 条件 : Perform JOIN in Subquery/DetachedCriteria

hibernate - Hibernate中如何将事务绑定(bind)到多个线程?

java - 如何将 Terracotta ehcache 与 hibernate 集成

java - JCombobox键盘输入速度

java - Android TV Leanback Exoplayer 视频缩放问题

java - 简单日期格式java模式

java - Spring JdbcTemplate 可以等待 oracle 存储过程完成多长时间

java - Spring无法处理 “multipart/form-data” POST请求(错误400 “Bad request”)

java - 在我的示例中如何模拟具有静态字段的类?