当前位置: 首页 > news >正文

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}]
http://www.cnnetsun.cn/news/89336.html

相关文章:

  • 商家福音!用PHP对接快递鸟接口,一键搞定单号所属快递识别
  • YT29B凿岩机吕梁精准检测稳定性能解析
  • 26、网络连接与安全全解析
  • 2025.12.16 HSRP双机热备
  • 万全智能RFID模块设备他们产品档次怎么样
  • RuoYi v1.2.0 全端开发神器:让多端适配从未如此简单!
  • 少儿编程Scratch3.0教程——03 外观积木(基础知识)
  • libxslt XSLT转换库:鸿蒙PC上的XML转换工具
  • GPU算力租赁推荐:低成本训练YOLO大模型
  • VonaJS是如何做到文件级别精确HMR(热更新)的?
  • 口碑好的货架哪里有好的
  • pytorch框架训练、推理、模块冻结等各种细节说明
  • Java毕设项目推荐-基于Java语言的茶叶销售系统的前端设计与实现基于SpringBoot+Vue茶叶销售系统的设计与实现【附源码+文档,调试定制服务】
  • 大数据生态核心组件语法与原理详解
  • UVa 11617 An Odd Love
  • LobeChat能否对接Slack?团队协作平台集成方案
  • 集团宽带是什么意思?企业如何选择合适的宽带方案?
  • 运维外包的公司靠谱吗?企业真能省心?
  • HunyuanVideo-Foley:AI让视频自动配声
  • 信息安全技术与Kali Linux
  • GEO系统:多区域搜索排名监控与品牌形象统一维护解决方案
  • 17、Apache服务器的代理配置、URL重写、自定义日志及性能监控
  • 18、Apache服务器性能测试与配置全解析
  • PostgreSQL 18 远程操作实战:从连接到备份的操作实践记录
  • S33-装一个Server2016+PCS7虚拟机
  • LobeChat能否部署在腾讯云CVM?国产云服务商适配教程
  • 本地使用ComfyUI运行Stable Diffusion 3.5
  • 力扣(LeetCode) 27: 移除元素 - 解法思路
  • 国内企业在泰国的三大机遇与四大挑战:玛雅出海东南亚的破局之道
  • 手把手教你部署LobeChat镜像,打造专属AI助手门户