使用springboottest和h2来构建数据库测试的采坑记录

2023-11-04 08:08

本文主要是介绍使用springboottest和h2来构建数据库测试的采坑记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 现状
  • 为啥要做
  • 我们的效果
  • 遇到的问题
    • table找不到
    • insert into value 不支持
    • 不支持json列
    • create database 不支持
    • 判断表是否存在有问题
    • 获取最后insert 的id
    • insert into 的字符串 不能使用双引号
    • 不同connection创建的database无法被看见

现状

因为项目关系和人力关系, 代码写的比较快而且质量不是很好. bug比较多 基本功能总是有问题(某些场景下) 所以现在想快速补齐测试短板.

为啥要做

想看看如何将spring boot test + db这套结合起来做测试… 因为我们是saas项目 所以更多的想法就是能不能采用内存数据库来方便UAT测试. 所以就有了下面的数据库对比和h2采坑记录

不同数据库对比:

H2DerbyHSQLDBMySQLPostgreSQL
Pure JavaYesYesYesNoNo
Memory ModeYesYesYesNoNo
Encrypted DatabaseYesYesYesNoNo
ODBC DriverYesNoNoYesYes
Fulltext SearchYesNoNoYesYes
Multi Version ConcurrencyYesNoYesYesYes
Footprint (embedded)~2 MB~3 MB~1.5 MB
Footprint (client)~500 KB~600 KB~1.5 MB~1 MB~700 KB

我们的效果

依赖springboot test 可以很方便的对整个应用的各个层级的代码做测试而且不用担心有问题

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//...
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;//@Ignore
@RunWith(SpringRunner.class)
@SpringBootTest
public class UseMemDbDerbyTest {Log LOG = LogFactory.getLog(UseMemDbDerbyTest.class);// 可以在这里做一些针对UAT测试的一些设置啥的static {Constants.COREDB = "testdb";System.setProperty("kb.config", "/Users/edward/projects/kb/config/kb-local-uat.config");try {LayeredConf.getInstance().load(System.getProperty("kb.config"));}catch (IOException e) {e.printStackTrace();}}// 自动注入的对象  可以很方便的拿来测试 只要是被springboot管理的@AutowiredAccountService accountService;@AutowiredRpcSessionController addSessionController;@Testpublic void test() throws Exception {LOG.info("Step 1: prepare account");Account a = prepareAccount();}Account prepareAccount() {AccountCatalog.initialize();accountService.delete(Account.getExternalId(Environment.ACCOUNT_ID_TEST));JSONObject o = new JSONObject();o.put("name", "PerfTest");return accountService.create(o.toString());}}
kb.config中的配置(可以理解为application.properties), 我们是自己写的 所以key 和 spring boot的不一样 但是不影响
database.url=jdbc:h2:mem:a1;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;
database.username=
database.password=
database.initDb = true
database.driver=org.h2.Driver

build.gradle中的依赖:

        testCompile 'org.apache.logging.log4j:log4j-api:2.8'testCompile 'org.apache.logging.log4j:log4j-core:2.8'testCompile 'org.apache.logging.log4j:log4j-slf4j-impl:2.8'testCompile 'org.springframework.boot:spring-boot-starter-log4j2:2.1.0.RELEASE'testCompile 'junit:junit:4.11'testCompile 'org.springframework.boot:spring-boot-starter-test:2.1.0.RELEASE'testCompile 'com.h2database:h2:1.4.197'

遇到的问题

table找不到

原因是内存表再创建后连接关闭了就没了. 而一般是多个连接, 所以在url中加入:

jdbc:h2:mem:;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;

DB_CLOSE_DELAY 指定等jvm退出后关闭. DATABASE_TO_UPPER 不让h2 自动转大写db名称.

insert into value 不支持

注意是insert into value 而不是 insert into values… mysql支持前者 而h2不支持. 修改下使用的sql即可. 标准的sql就是insert into xxx values (1, 2, 3)

不支持json列

换成varchar2 前提是没使用json相关功能.

create database 不支持

H2 使用的是create schema if not exists xxxx; 并且不支持设置字符集(像mysql方式).

判断表是否存在有问题

应该是mysql没有按方式来… 正确的java代码:

    public static boolean tableExists(Connection conn, String dbName, String tableName) throws SQLException {String[] types = {"TABLE"};ResultSet rs = null;try {//  注意这里的参数顺序rs = conn.getMetaData().getTables(null, dbName, tableName, types);if(rs.next()) {return true;}else {return false;}}finally {closeQuietly(rs);}}

但是mysql也支持如下这样的, h2不支持:注意这里的参数顺序

rs = conn.getMetaData().getTables(dbName, null, tableName, types);  

获取最后insert 的id

对于有主键的, mysql支持 你手动输入某个表的id 字段, 然后返回, 但是 h2不支持这种case. 比如:

create table tttt (id bigint not null primary key auto_increment, a int);
        PreparedStatement ps2 = mysqlConn.prepareStatement("insert into uat.tttt values(1, 2)", Statement.RETURN_GENERATED_KEYS);ps2.executeUpdate();ResultSet psRs2 = ps2.getGeneratedKeys();while (psRs2.next()) {System.out.println("Found one record");System.out.println(psRs2.getLong(1));}

mysql能够查询返回即便你手动指定的id=1. 但是h2 不支持. 参考: 这里

insert into 的字符串 不能使用双引号

insert into testdb.kbgroups values (1, 'abc', '')

mysql支持使用双引号:

insert into testdb.kbgroups values (1, "abc", "")

参考这里: http://www.h2database.com/html/grammar.html#string

不同connection创建的database无法被看见

        Class.forName("org.h2.Driver");Connection connection = DriverManager.getConnection("jdbc:h2:mem:;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;");Statement s = connection.createStatement();s.execute("create schema testdb");s.execute("create table testdb.testt(id bigint not null primary key auto_increment, a int)");PreparedStatement ps = connection.prepareStatement("insert into testdb.testt values (111, 33)", Statement.RETURN_GENERATED_KEYS);int in = ps.executeUpdate();connection.commit();Connection connection2 = DriverManager.getConnection("jdbc:h2:mem:;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;");System.out.println("use connection1 test:" + tableExists(connection, "testdb", "testt"));System.out.println("use connection2 test:" + tableExists(connection2, "testdb", "testt"));public static boolean tableExists(Connection conn, String dbName, String tableName) throws SQLException {String[] types = {"TABLE"};ResultSet rs = null;try {rs = conn.getMetaData().getTables(null, dbName, tableName, types);if(rs.next()) {return true;}else {return false;}}finally {if (rs != null) {rs.close();}}}

输出:

use connection1 test:true
use connection2 test:false

可以看见确实无法看见另外连接创建的:

​ In-Memory

jdbc:h2:mem:test multiple connections in one process
jdbc:h2:mem: unnamed private; one connection

or certain use cases (for example: rapid prototyping, testing, high performance operations, read-only databases), it may not be required to persist data, or persist changes to the data. This database supports the in-memory mode, where the data is not persisted.In some cases, only one connection to a in-memory database is required. This means the database to be opened is private. In this case, the database URL is jdbc:h2:mem: Opening two connections within the same virtual machine means opening two different (private) databases.Sometimes multiple connections to the same in-memory database are required. In this case, the database URL must include a name. Example: jdbc:h2:mem:db1. Accessing the same database using this URL only works within the same virtual machine and class loader environment.To access an in-memory database from another process or from another computer, you need to start a TCP server in the same process as the in-memory database was created. The other processes then need to access the database over TCP/IP or TLS, using a database URL such as: jdbc:h2:tcp://localhost/mem:db1.By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use 

这条还是比较奇怪的~. 上面也说清楚了内存模式的一些限制/规则:

  1. 内存模式, 数据不会持久化

  2. 如果想要one connection one database, 使用:jdbc:h2:mem 数据库在连接关闭后关闭. 这样的话即便是同一个jvm的2个连接看到的也是不同的数据库.

  3. 如果想在jvm内部共享, 就必须:jdbc:h2:mem:db1 这样. (在jvm级别的classloader共享)

  4. 关于连接关闭数据库消失可以设置: ;DB_CLOSE_DELAY=-1 到url

    我创建了issue

这篇关于使用springboottest和h2来构建数据库测试的采坑记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/344407

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

MySQL数据库中ENUM的用法是什么详解

《MySQL数据库中ENUM的用法是什么详解》ENUM是一个字符串对象,用于指定一组预定义的值,并可在创建表时使用,下面:本文主要介绍MySQL数据库中ENUM的用法是什么的相关资料,文中通过代码... 目录mysql 中 ENUM 的用法一、ENUM 的定义与语法二、ENUM 的特点三、ENUM 的用法1

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是