使用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

相关文章

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

C#中Guid类使用小结

《C#中Guid类使用小结》本文主要介绍了C#中Guid类用于生成和操作128位的唯一标识符,用于数据库主键及分布式系统,支持通过NewGuid、Parse等方法生成,感兴趣的可以了解一下... 目录前言一、什么是 Guid二、生成 Guid1. 使用 Guid.NewGuid() 方法2. 从字符串创建

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

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编程客