Dou*_*oug 4 java junit spring h2 spring-boot
我正在尝试创建一个使用嵌入式H2数据库的测试。但是我必须更改spring.datasource.url,我不能使用spring boot创建的默认值。(这是因为我必须将H2数据库的模式更改为MYSQL)
这是我的test class
:
@JdbcTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class DemoApplicationTests {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
DataSource dataSource;
@Test
public void contextLoads() {
System.out.println(dataSource);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的application-test.properties
:
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
spring.datasource.username=dbuser
spring.datasource.password=dbpass
Run Code Online (Sandbox Code Playgroud)
我的依赖:
compile('org.springframework.boot:spring-boot-starter-batch')
runtime('com.h2database:h2')
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '1.5.3.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.5.3.RELEASE'
Run Code Online (Sandbox Code Playgroud)
控制台输出:
启动嵌入式数据库:url ='jdbc:h2:mem:bfad6b71-3e2d-4a47-a32d-c76988b3c5f6; DB_CLOSE_DELAY = -1; DB_CLOSE_ON_EXIT = false',用户名='sa'
我希望网址是这样的:jdbc:h2:mem:testdb
,我也希望它使用MODE=MYSQL
设置。
我试图关注这篇文章,但是没有用。
Spring Boot 的@DataJdbcTest
、@DataJpaTest
、@JdbcTest
through@AutoConfigureTestDatabase
都会最终调用TestDatabaseAutoConfiguration
,而默认情况下,这又会使用自动生成的唯一名称配置内存中的嵌入式数据库实例。
如果您碰巧使用带有@Table
非空catalog
属性的 JPA 实体,这可能会给您带来问题,因为 H2 要求目录名称与其数据库名称相同。
正如戴恩·萨沃特(Dane Savot)在回答中所说
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
Run Code Online (Sandbox Code Playgroud)
将解决该测试类的问题,但如果您想全局解决它,请添加
spring.test.database.replace=none
Run Code Online (Sandbox Code Playgroud)
到你的src/test/resources/application.properties
或.yaml
. 该属性控制@AutoConfigureTestDatabase.replace
的行为。
小智 6
您需要告诉Spring不要用以下内容替换随机嵌入式数据库名称:
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
然后,它将选择您在application.properties中声明的属性。
请随时赞扬它是否对您有用。
归档时间: |
|
查看次数: |
1870 次 |
最近记录: |