【问题标题】:RestController test fails with h2 databaseRestController 测试失败,使用 h2 数据库
【发布时间】:2018-04-03 09:21:50
【问题描述】:

我正在尝试使用h2 数据库在我的Spring boot 应用程序中对我的RestController 运行测试。 这是一些代码:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
public class E2E_EconomicOperatorAPIControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test public void test_newEconomicOperator() {
     //staff
     }
}

但是当我运行它时,我得到了这个错误:

2018-04-03 12:16:57.084  WARN 14332 --- [       Thread-7] o.s.b.f.support.DisposableBeanAdapter    : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-196]

这是我的属性文件:

spring.datasource.url=jdbc:h2:mem:testdb;MODE=Oracle;DB_CLOSE_DELAY=-1

logging.level.org.gso.admin=DEBUG
logging.level.gso.gd.client=INFO
logging.level.org.springframework.web.client=WARN
logging.level.org.springframework=WARN
logging.level.org.thymeleaf=WARN
logging.level.root=WARN

【问题讨论】:

  • 尝试更新您的数据源 URL,例如:jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE 它出现时没有退出关闭 h2 的数据库自动关闭的子句
  • 是的,我在另一个 stackoverflow 问题中看到了这个答案,但徒劳无功。已经添加到我的属性文件中
  • 这能解决问题吗?

标签: spring spring-boot junit4 h2


【解决方案1】:

实际上,您不需要为嵌入式 h2 数据库设置任何属性,因为引导会为您配置(此外,我认为您应该省略 MODE=Oracle 标志)。这是我所做的: 将以下依赖项放入您的.pom

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>test</scope>
</dependency>

注意范围。这将在测试期间加载对您的类路径的依赖项(仅此而已)。然后,您应该确保每个环境都有一个 application.properties 文件,您可以在其中设置数据库,而您永远不需要真正的数据库。

以我的应用为例:

application-dev.properties:(注意:我想要一个真正的开发数据库,​​所以我输入了 prostgres...)

spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=validate
spring.database.driverClassname=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://192.168.1.100:5432/winecellar
spring.datasource.username=winecellar
spring.datasource.password=winecellar

application-test.properties:

spring.jpa.database=H2
spring.jpa.show-sql=true 
spring.jpa.hibernate.ddl-auto=none
spring.database.driverClassname=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.username=sa
spring.datasource.password=

我有一个用于生产设置的类似文件(也使用 postgres...)

然后,只要您像使用 @ActiveProfiles("test") 一样对其进行注释,就可以了。

【讨论】:

  • 我也在本地以开发模式使用 H2,因此它在我的 pom 中的范围是“运行时”,因此它也可用于测试范围(根据文档)
  • 应该没问题。只需相应地更改属性文件
  • 是的,一切都已经修复,我的项目已经运行良好,但这是我第一次尝试使用 resttemplate。顺便说一句,我在测试我的服务时没有收到此错误
猜你喜欢
  • 2020-05-08
  • 2017-04-13
  • 2015-11-20
  • 2016-09-04
  • 2012-12-12
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多