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}]
相关推荐
她说..5 小时前
Spring AOP场景5——异常处理(附带源码)
java·数据库·后端·spring·springboot·spring aop
dllxhcjla5 小时前
MySQL单表
数据库·mysql
叫我龙翔5 小时前
【Redis】从零开始掌握redis --- 认识redis
数据库·redis·缓存
小马爱打代码5 小时前
慢SQL:查询、定位分析解决的完整方案
数据库·sql
Alaia.5 小时前
【T级别数据迁移】Oracle 数据库迁移操作手册(oracle-migrate-bash)
数据库·oracle·bash
Pocker_Spades_A5 小时前
时序数据库选型指南:用工程视角理解 Apache IoTDB
数据库·apache·时序数据库·iotdb
深海空无一人5 小时前
数据库进阶
数据库
心动啊1215 小时前
MySQL在python中的使用——连接方式及对对象的调用
数据库·mysql
橘颂TA5 小时前
【Linux】不允许你还不会——信号保存(3)
linux·服务器·网络·数据库