Spring boot Spring引导:从测试/资源中的模式填充h2 db

Spring boot Spring引导:从测试/资源中的模式填充h2 db,spring-boot,h2,Spring Boot,H2,在我的本地计算机上,我加载内存中的h2数据库,以便在安全的环境中启动spring boot应用程序,以下是属性: spring.datasource.url: jdbc:h2:mem:DB_TEST;Mode=Oracle spring.datasource.platform: h2 spring.jpa.hibernate.ddl-auto: none spring.datasource.continue-on-error: false spring.jpa.database-platform

在我的本地计算机上,我加载内存中的h2数据库,以便在安全的环境中启动spring boot应用程序,以下是属性:

spring.datasource.url: jdbc:h2:mem:DB_TEST;Mode=Oracle
spring.datasource.platform: h2
spring.jpa.hibernate.ddl-auto: none
spring.datasource.continue-on-error: false
spring.jpa.database-platform: org.hibernate.dialect.Oracle10gDialect
然后,在src/main/resources中,我有一个文件schema-h2.sql,其中包含我的本地数据库初始化

这很好,但我还想执行一些junit测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

@Autowired
private MyController controller;

@Test
public void myTest(){
     controller.doSomething();
}
这也很好,可以看到schema-h2.sql

无论如何,我认为最好将schema-h2.sql放在src/test/resources中,因为它只能在本地环境中使用。这样做还允许maven将其从最终构建中排除,这也很好

无论如何,如果我把它放在那里,测试会继续工作……但是主应用程序会因为找不到schema-h2.sql而中断

如何修改上述属性以指定必须在test/resources文件夹中搜索shema-h2.sql


感谢在正常模式下,属性文件放在src/main/resources中, 对于测试方法,属性文件位于src/test/resources文件夹中

通过尝试运行一个测试类,eclipse运行它在src/main/resources和src/test/resources下找到的以.sql结尾的每个文件(因此包含一个创建表或插入数据的脚本)。 因此,如果您将脚本文件schema.sql(包含创建表的脚本:create table..)放在两个文件夹中,您将得到一个“table ready exits”错误,如果您允许jut one,测试将顺利运行。 如果将脚本文件(在表中插入数据)放在两个文件夹中,则两个脚本都将运行


您还可以使用存储库中的
@PropertySource(“…”)
告诉spring在哪里可以找到要使用的属性文件

如果您使用不同的应用程序配置文件,您可以将默认配置文件与
spring.datasource.initialization mode=always
一起使用,以便在测试阶段加载模式,但在运行应用程序时,您可以将
spring.datasource.initialization mode=never
与另一个配置文件(如
dev
或其他配置文件)一起使用。通过这种方式,您可以为特定概要文件启用shcema.sql功能,但其他概要文件对dev和test都是相同的…我也不想在整个项目中克隆h2-schema.sql:(尝试使用此链中建议的内容)您是否尝试在测试类中查看过
@AutoConfigureTestDatabase