JAVA_Spring

SpringBoot1 开发之h2内存数据库(单元测试使用)

2018-11-03  本文已影响0人  kason_zhang

一般开发时,可以准备两套数据库, 真实的数据操作的数据库, 测试使用的内存数据库(比如h2)
SpringBoot中针对这个h2数据库需要加入:

<!--内存数据库,测试使用 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

配置文件:
application

spring.profiles.active=dev

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=validate

logging.level.org.hibernate.SQL=debug

# Session 会话存储类型
spring.session.store-type=hash_map

# 关闭http 基本验证
security.basic.enabled=false

spring.profiles.active=dev说明我们使用开发版本的配置文件
application-dev.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xunwu?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root

h2 内存数据库测试使用application-test.properties

spring.datasource.driver-class-name=org.h2.Driver
# 内存模式
spring.datasource.url=jdbc:h2:mem:test

# 指定我们预先创建的h2数据库 的具体数据
spring.datasource.schema=classpath:db/schema.sql
spring.datasource.data=classpath:db/data.sql

完成上述配置后, 单元测试类需要新增:@ActiveProfiles("test"),代表激活使用application-test.properties

@RunWith(SpringRunner.class)
@SpringBootTest
@Configuration
@ActiveProfiles("test")
public class KasonProjectApplicationTests {



}
上一篇 下一篇

猜你喜欢

热点阅读