![](/img/trans.png)
[英]Spring Boot DataJpaTest unit test reverting to H2 instead of mySql
[英]How to add the mode=mysql to embedded H2 DB in Spring Boot 1.4.1 for @DataJpaTest?
我在执行 junit 测试时使用 schema.sql 文件创建我的 sql 模式时遇到一些问题,而此模式包含 mysql 特定表达式。 我必须将mode=mysql
添加到 H2 url。
例如像这样的东西: jdbc:h2:mem:testd;MODE=MYSQL
但是 Spring boot 自动使用枚举 org.springframework.boot.autoconfigure.jdbc.EmbeddedDatabaseConnection 中定义的 url 及其 url
jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
。
我已经尝试过类似的方法来让它工作,但是 spring 没有从我的 test-application.properties 中获取spring.datasource.url=jdbc:h2:mem:testdb;MODE=MYSQL
。 我的 test-application.properties 中的所有其他设置都已成功读取。
如果我让 spring/hibernate 在我的实体中使用 javax.persistence 注释创建模式(没有 schema.sql 文件),一切正常。
有添加模式的简单方法吗?
放
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
在 application-test.properties 中,加上
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("test")
在测试课上
我遇到了同样的问题。 运行测试时它不会获取 url。 我正在使用 flyway 来管理我的脚本。 通过执行以下几个步骤,我能够让所有这些一起工作。
在 src/test/resources/db/migration 中创建了一个V1_init.sql
脚本,使其成为 flyway 运行的第一个脚本。
SET MODE MYSQL; /* another h2 way to set mode */
CREATE SCHEMA IF NOT EXISTS "public"; /* required due to issue with flyway --> https://stackoverflow.com/a/19115417/1224584*/
更新了application-test.yaml
以包含模式名称 public:
flyway:
schemas: public
确保测试指定了配置文件: @ActiveProfiles("test")
我已经尝试过类似的方法来让它工作,但是 spring 没有从我的 test-application.properties 中获取 spring.datasource.url=jdbc:h2:mem:testdb;MODE=MYSQL
您是否尝试附加此参数而不是重写现有参数?
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
我的 test-application.properties 中的所有其他设置都已成功读取。
我认为该文件应该命名为application-test.properties
。
我能够使用此配置运行它:
# for integration tests use H2 in MySQL mode
spring.datasource.url=jdbc:h2:mem:testdb;DATABASE_TO_LOWER=TRUE;MODE=MySQL;
spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
这里的主要技巧是强制 Hibernate 为 MariaDB 方言生成 SQL 脚本,否则 Hibernate 会尝试使用 H2 方言,而 H2 已经在等待类似 MySQL 的命令。
我还尝试为 MariaDB 10.3 使用更新鲜的MariaDB103Dialect
,但它无法正常工作。
您需要在 h2 上设置MYSQL
模式并禁用替换嵌入式数据库的数据源 url:
修改application-test.yaml
spring:
datasource:
url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;MODE=MYSQL
test:
database:
replace: NONE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.