springboot集成h2内存数据库运行测试用例

springboot集成h2内存数据库运行测试用例

首先引入我们的依赖

引入h2的依赖和spring的依赖

groovy 复制代码
dependencies {
	implementation 'org.springframework.boot:spring-boot-h2console'
	implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    // 引入h2内存数据库
	runtimeOnly 'com.h2database:h2'
	testImplementation 'org.springframework.boot:spring-boot-starter-data-jdbc-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
	testImplementation platform('org.junit:junit-bom:5.13.4')
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

完整的配置

build.gradle

groovy 复制代码
plugins {
	id 'java'
	id 'groovy'
	id 'org.springframework.boot' version '4.0.0'
	id 'io.spring.dependency-management' version '1.1.7'
}

group = 'local'
version = '0.0.1-SNAPSHOT'
description = ''

java {
	toolchain {
		languageVersion = JavaLanguageVersion.of(25)
	}
}

sourceSets {
    main {
        groovy {
            srcDirs = ['src/main/groovy', 'src/main/java']
        }
    }
    test {
        groovy {
            srcDirs = ['src/test/groovy', 'src/test/java']
        }
    }
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-h2console'
	implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
	// jetty替换tomcat
    implementation("org.springframework.boot:spring-boot-starter-jetty")
	implementation ('org.springframework.boot:spring-boot-starter-webmvc')
	implementation 'org.apache.groovy:groovy'
    // 引入h2内存数据库
	runtimeOnly 'com.h2database:h2'
	testImplementation 'org.springframework.boot:spring-boot-starter-data-jdbc-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
	testImplementation platform('org.junit:junit-bom:5.13.4')
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

configurations {
    implementation {
        // 全局排除Tomcat依赖,确保使用Jetty
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
    }
}

tasks.withType(GroovyCompile).configureEach {
    // 启用groovy的增量编译,和注解处理器冲突!
    options.incremental = true
    options.incrementalAfterFailure = true
}

tasks.withType(JavaCompile).configureEach {
    // 指定java版本
    options.release = 25
}

tasks.named('jar') {
    // 设置重复文件处理策略
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}

tasks.named('bootJar') {
    // 设置重复文件处理策略
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}

tasks.named('test') {
    useJUnitPlatform()
    jvmArgs += '-XX:+EnableDynamicAgentLoading'
    jvmArgs += '-XX:+UseCompactObjectHeaders'
    // 测试输出配置
    testLogging {
        events "passed", "skipped", "failed", "standardOut", "standardError"
        // 显示System.out和System.err的输出
        showStandardStreams = true
        showCauses = true
        showExceptions = true
        showStackTraces = true
        exceptionFormat = 'full'
    }
    // 在控制台实时显示输出
    outputs.upToDateWhen { false }
}

settings.gradle

groovy 复制代码
rootProject.name = 'my_sb4'
enableFeaturePreview('GROOVY_COMPILATION_AVOIDANCE')

然后在spring的配置文件中配置数据库连接

注意要添加这些参数

  1. DB_CLOSE_DELAY=-1 : 避免没有连接时内存数据库关闭导致数据丢失
  2. MODE=MySQL : 使用mysql模式
  3. DATABASE_TO_LOWER=TRUE 和 CASE_INSENSITIVE_IDENTIFIERS=FALSE : 兼容mysql默认的忽略大小写模式
  4. LOCK_TIMEOUT=30 : 设置锁超时时间,避免一直死锁(单位秒)

内存数据库配置如下

application-test.yml

yaml 复制代码
# application-test.yml
spring:
  datasource:
    # 内存数据库连接配置,注意参数
    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=MySQL;DATABASE_TO_LOWER=TRUE;CASE_INSENSITIVE_IDENTIFIERS=FALSE;LOCK_TIMEOUT=30
    driver-class-name: org.h2.Driver
    username: sa
    password: ""
  h2:
    console:
      # 开启h2控制台;通过 localhost:8080/h2-console 访问
      enabled: true
      path: /h2-console
  sql:
    init:
      # 初始化数据库方式,在运行测试用例时设置为always
      mode: always
      # 初始化数据库脚本位置
      schema-locations: classpath:db/schema.sql
      data-locations: classpath:db/data.sql
      continue-on-error: false

通用配置如下

application.yml

yaml 复制代码
spring:
  application:
    name: my_sb4
server:
  port: 8080
  servlet:
    context-path: /
# 配置日志
logging:
  level:
    org.springframework.boot: INFO
    org.eclipse.jetty: WARN
    org.springframework.jdbc: DEBUG
  pattern:
    console: "%d{yy-MM-dd HH:mm:ss.S} %highlight(%-5p) %c{1}:%L - %m%n"

然后创建我们的初始化脚本

schema.sql

sql 复制代码
CREATE TABLE IF NOT EXISTS T_USERS (
    ID BIGINT AUTO_INCREMENT PRIMARY KEY,
    USERNAME VARCHAR(255) NULL
);

data.sql

sql 复制代码
INSERT INTO T_USERS (USERNAME) VALUES ('张三');
INSERT INTO T_USERS (USERNAME) VALUES ('李四');
INSERT INTO T_USERS (USERNAME) VALUES ('王五');

现在编写我们的测试用例

我们希望在测试用例中查询数据,就可以整样

groovy 复制代码
package local.my_sb4

import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.test.context.ActiveProfiles
import tools.jackson.databind.json.JsonMapper
@SpringBootTest
@ActiveProfiles("test")
class MySb4ApplicationTest {
    @Autowired
    private JdbcTemplate jdbcTemplate
    @Autowired
    JsonMapper jsonMapper
    @Test
    void testContextLoads() {
        println jsonMapper.writeValueAsString(jdbcTemplate.queryForList('''select * from t_Users '''))
        // 我们自己的表默认都在public下,通常不需要改变他们
        println jsonMapper.writeValueAsString(jdbcTemplate.queryForList('''select * from INFORMATION_SCHEMA.TABLES where table_schema!='information_schema' '''))
    }

}

运行我们的用例将正常输出日志

plain 复制代码
25-12-16 17:26:30.4 DEBUG o.s.j.c.JdbcTemplate:470 - Executing SQL query [select * from t_Users ]
25-12-16 17:26:30.4 DEBUG o.s.j.d.DataSourceUtils:117 - Fetching JDBC Connection from DataSource
[{"id":1,"username":"张三"},{"id":2,"username":"李四"},{"id":3,"username":"王五"}]
25-12-16 17:26:30.5 DEBUG o.s.j.c.JdbcTemplate:470 - Executing SQL query [select * from INFORMATION_SCHEMA.TABLES where table_schema!='information_schema' ]
25-12-16 17:26:30.5 DEBUG o.s.j.d.DataSourceUtils:117 - Fetching JDBC Connection from DataSource
[{"table_catalog":"testdb","table_schema":"public","table_name":"t_users","table_type":"BASE TABLE","is_insertable_into":"YES","commit_action":null,"storage_type":"MEMORY","remarks":null,"last_modification":30,"table_class":"org.h2.mvstore.db.MVTable","row_count_estimate":3}]
相关推荐
定偶13 分钟前
MySQL安装
数据库·mysql
Zzzzmo_16 分钟前
【MySQL】数据库约束 及 表的设计
数据库·mysql
我爱娃哈哈16 分钟前
SpringBoot + Flowable + 自定义节点:可视化工作流引擎,支持请假、报销、审批全场景
java·spring boot·后端
码云数智-大飞34 分钟前
Oracle RAS:AI时代守护企业数据安全的智能盾牌
数据库·人工智能·oracle
bubuly38 分钟前
软件开发全流程注意事项:从需求到运维的全方位指南
大数据·运维·数据库
韩师学子--小倪1 小时前
SpringBoot 优雅停服
spring boot·tomcat
我真的是大笨蛋1 小时前
Redo Log详解
java·数据库·sql·mysql·性能优化
fengxin_rou1 小时前
Redis 从零到精通:第一篇 初识redis
数据库·redis·缓存
爱学习的阿磊2 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
m0_736919102 小时前
Python面向对象编程(OOP)终极指南
jvm·数据库·python