news 2026/7/7 10:16:37

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
springboot集成h2内存数据库运行测试用例

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

首先引入我们的依赖

引入h2的依赖和spring的依赖

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'testImplementationplatform('org.junit:junit-bom:5.13.4')testImplementation'org.junit.jupiter:junit-jupiter'}

完整的配置

build.gradle

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替换tomcatimplementation("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'testImplementationplatform('org.junit:junit-bom:5.13.4')testImplementation'org.junit.jupiter:junit-jupiter'}configurations{implementation{// 全局排除Tomcat依赖,确保使用Jettyexclude group:'org.springframework.boot',module:'spring-boot-starter-tomcat'}}tasks.withType(GroovyCompile).configureEach{// 启用groovy的增量编译,和注解处理器冲突!options.incremental=trueoptions.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=trueshowCauses=trueshowExceptions=trueshowStackTraces=trueexceptionFormat='full'}// 在控制台实时显示输出outputs.upToDateWhen{false}}

settings.gradle

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

# application-test.ymlspring:datasource:# 内存数据库连接配置,注意参数url:jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=MySQL;DATABASE_TO_LOWER=TRUE;CASE_INSENSITIVE_IDENTIFIERS=FALSE;LOCK_TIMEOUT=30driver-class-name:org.h2.Driverusername:sapassword:""h2:console:# 开启h2控制台;通过 localhost:8080/h2-console 访问enabled:truepath:/h2-consolesql:init:# 初始化数据库方式,在运行测试用例时设置为alwaysmode:always# 初始化数据库脚本位置schema-locations:classpath:db/schema.sqldata-locations:classpath:db/data.sqlcontinue-on-error:false

通用配置如下

application.yml

spring:application:name:my_sb4server:port:8080servlet:context-path:/# 配置日志logging:level:org.springframework.boot:INFOorg.eclipse.jetty:WARNorg.springframework.jdbc:DEBUGpattern:console:"%d{yy-MM-dd HH:mm:ss.S} %highlight(%-5p) %c{1}:%L - %m%n"

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

schema.sql

CREATETABLEIFNOTEXISTST_USERS(IDBIGINTAUTO_INCREMENTPRIMARYKEY,USERNAMEVARCHAR(255)NULL);

data.sql

INSERTINTOT_USERS(USERNAME)VALUES('张三');INSERTINTOT_USERS(USERNAME)VALUES('李四');INSERTINTOT_USERS(USERNAME)VALUES('王五');

现在编写我们的测试用例

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

packagelocal.my_sb4importorg.junit.jupiter.api.Testimportorg.springframework.beans.factory.annotation.Autowiredimportorg.springframework.boot.test.context.SpringBootTestimportorg.springframework.jdbc.core.JdbcTemplateimportorg.springframework.test.context.ActiveProfilesimporttools.jackson.databind.json.JsonMapper@SpringBootTest@ActiveProfiles("test")classMySb4ApplicationTest{@AutowiredprivateJdbcTemplate jdbcTemplate@AutowiredJsonMapper jsonMapper@TestvoidtestContextLoads(){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' '''))}}

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

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}]
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/7 8:31:55

【期末复习02】-分析题和改错题作业

文章目录【期末复习02】-分析题和改错题项目结构分析题01分析题02分析题03分析题04二、程序改错题(20分)项目结构改错题01改错题02【期末复习02】-分析题和改错题 项目结构 分析题01 分析题02 分析题03 分析题04 二、程序改错题(20分) 项目结构 改错题01 考察知识点&#xff…

作者头像 李华
网站建设 2026/7/7 11:31:56

8亿参数Seed-Coder重塑智能编程未来

Seed-Coder-8B:当代码遇见“懂你”的AI 在某个深夜的调试现场,开发者盯着屏幕上第17个测试失败的用例,手指悬停在键盘上犹豫不决——变量命名是否一致?边界条件是否遗漏?API调用是否有误?这种熟悉的窒息感&…

作者头像 李华
网站建设 2026/7/7 8:11:09

AI超级员工源头厂商有哪些?对比测评,区别有哪些?

市面上做的最好的ai员工源头厂商有青否ai超级员工和炼刀ai员工,那我们来对比一下两者之间有哪些区别?有哪些有优劣势?青否ai超级员工是青否科技研发国内最落地的ai员工系统,通过手机小程序语音指令远程控制电脑,替代人…

作者头像 李华
网站建设 2026/7/7 17:13:38

LobeChat能否用于生成APP界面文案?UX写作助手

LobeChat能否用于生成APP界面文案?UX写作助手 在移动产品竞争日益激烈的今天,一句恰到好处的按钮文案,可能就是用户完成转化的关键。但现实是,很多团队仍在靠“拍脑袋”决定“确定吗?”还是“确认一下?”&a…

作者头像 李华
网站建设 2026/7/7 17:42:36

Docker安装最佳实践:配置清华源加速TensorFlow镜像构建

Docker安装最佳实践:配置清华源加速TensorFlow镜像构建 在人工智能项目开发中,一个常见的痛点是:当你兴致勃勃地准备启动一个基于 TensorFlow 的实验时,执行 docker pull tensorflow/tensorflow:latest 后,终端却卡在…

作者头像 李华
网站建设 2026/7/7 9:20:40

Dify智能体平台在未来AI生态中的定位展望

Dify智能体平台在未来AI生态中的定位展望 在企业纷纷拥抱“AI原生”转型的今天,一个现实问题摆在面前:如何让大模型的能力真正落地到具体业务中?我们早已见证了GPT类模型在生成文本、编写代码方面的惊艳表现,但这些能力若无法被系…

作者头像 李华