首页 > 解决方案 > 用 H2 测试 SpringBoot 数据库的正确方法是什么?

问题描述

我正在尝试使用 Mybatis 使用 H2 内存数据库运行 Springboot 测试。到目前为止我已经完成了

  1. 在 application-test.properties 中配置 h2 DB
  2. 添加注释
@SpringBootTest, @TestPropertySource (locations = "TEST_APPLICATION_PROPERTIES_LOCATION")
  1. 自动装配 dao 和 serviceImpl bean
  2. 将 seed.sql 和 purge.sql 添加到测试类
@SqlGroup({
        @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:/database/seed.sql"),
        @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:/database/purge.sql") })

尽管采取了上述措施,我仍然有两个问题

  1. 我无法检索使用seed.sql 输入的用户。我创建了一个 id="admin"、pw="admin" 的用户,并尝试使用 findById("admin") 进行检索。但它总是返回 null。

  2. 在使用@test 进行调试时,我无法打开 h2 DB。我根本无法使用 localhost:8080/h2-console 访问 h2(路径已明确写入 application-test.properties)

我应该采取什么额外措施来测试带有 h2 的 SpringBoot 吗?

标签: databaseunit-testingspring-booth2mybatis

解决方案


添加 spring.h2.console.enabled=true 您的属性文件。


推荐阅读