Java Spring4JUnit测试:将SQL加载到H2DB

Java Spring4JUnit测试:将SQL加载到H2DB,java,spring,junit,spring-test,Java,Spring,Junit,Spring Test,我正在尝试为SpringBoot(Spring4)应用程序编写测试 我的Junit测试类是这样配置的,以允许自动连线 @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringApp.class) public class MyServiceTest { ... 我的src/main/resources/application.properties如下 spring.jpa.d

我正在尝试为SpringBoot(Spring4)应用程序编写测试

我的Junit测试类是这样配置的,以允许自动连线

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringApp.class)
public class MyServiceTest {
...
我的
src/main/resources/application.properties
如下

spring.jpa.database=POSTGRESQL
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update

spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost/mydb
spring.datasource.username=BNF0016779
spring.datasource.password=
在测试上下文中,src/test/resources/application.properties只是空的

在中可以像往常一样查询数据库,创建对象

但是我想创建一个datainitsql

从一个奇怪的行为开始,Spring似乎加载了类路径中的任何“schema.sql”。 不需要以下内容

//This is not required to execute schema.sql
@Configuration
public class DatabaseTestConfig {
    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .addScript("classpath:schema.sql")
            .build();
    }
}
然后,我无法从该SQL创建任何表。 始终接收
org.h2.jdbc.JdbcSQLException:表“我的表”已存在;SQL语句:

H2应该是内存中的DB,在两次启动之间不保留数据! 为什么我会收到这些错误

有什么想法吗?
谢谢,H2可以在内存中。但我假设它使用的默认数据源不是


您可以在
EmbeddedDatabaseBuilder
上设置
DataSourceFactory
,以生成一个
DataSource
,该数据源连接到一个url,例如
jdbc:h2:mem:test
,,默认情况下,Spring Boot将在类路径的根目录中执行一个名为
schema.sql
的文件。此外,SpringBoot还将自动为应用程序创建嵌入式数据库,除非您另有指示。有关详细信息,请参阅Spring Boot参考手册的“”部分

H2应该是内存中的DB,不能在两个数据库之间保留数据 启动

是和否

如果SpringBoot为您创建了一个嵌入式H2数据库,那么它将在内存中

然而,数据库实际上是
ApplicationContext
中的一个bean(就像任何其他Spring管理的组件一样)。因此,只要
ApplicationContext
存在,它就存在,而SpringTestContext框架在测试之间缓存上下文:这是它的主要特性之一。换句话说,嵌入式数据库不会在测试之间重新创建(除非您使用
@DirtiesContext
注释测试类或测试方法)。有关详细信息,请参阅Spring框架参考手册的章节

问候,


Sam(SpringTestContext框架的作者)

我很确定,默认情况下,它在memoryYeah中,刚刚检查了4.1.3.RELEASE的grepcode,默认情况下它在内存中,我的坏消息