快速测试Mybatis复杂sql,无需启动spring

快速测试mybatis的sql

当我们写完sql后,我们需要测试下sql是否符合预期,在填入各种参数后能否正常工作,尤其是对于复杂的sql.

一般我们测试可能是如下的代码:

由于需要启动spring,当项目较大的时候启动速度很慢,有些项目的启动时间超过30秒。导致测试sql速度很慢,改下sql重新再测试等很花时间。

如果只是单独测试sql是否正确,没必要启动spring容器,mybatis可以直接定义配置文件进行启动,测试代码如下

配置文件

这样我们可以直接测试mybatis的sql而不需要启动spring

速度非常快 如下:

基本上1,2秒钟就跑完了。 相比启动spring的测试效率提升很高。

生成testcase支持PageHelper分页插件

修改setUp方法加入interceptor即可

java 复制代码
SqlSessionFactory builder = new SqlSessionFactoryBuilder().build(UserMapperTest.class.getClassLoader().getResourceAsStream("mybatisTestConfiguration/UserMapperTestConfiguration.xml"));
        //you can use builder.openSession(false) to not commit to database
PageInterceptor interceptor = new PageInterceptor();
builder.getConfiguration().addInterceptor(interceptor);
mapper = builder.getConfiguration().getMapper(UserMapper.class, builder.openSession(true));

生成testcase支持mybatisplus

在生成的testcase中有一个setUp方法,将SqlSessionFactoryBuilder改成MybatisSqlSessionFactoryBuilder即可测试mybatisplus自带的一些方法

mybatisplus添加分页插件和乐观锁插件

在test类可以修改setUpMybatisDatabase 如下

scss 复制代码
@org.junit.BeforeClass
    public static void setUpMybatisDatabase() {
        SqlSessionFactory builder = new MybatisSqlSessionFactoryBuilder().build(SymphonyClientMapperTest.class.getClassLoader().
                getResourceAsStream("mybatisTestConfiguration/SymphonyClientMapperTestConfiguration.xml"));
        final MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        builder.getConfiguration().addInterceptor(interceptor);
        //you can use builder.openSession(false) to not commit to database
        mapper = builder.getConfiguration().getMapper(SymphonyClientMapper.class, builder.openSession(true));
    }

这样就可以快速测试mybatis的sql了.

也可以试试我写的Intellij下的MybatisCodeHelperPro插件,链接

插件可以自动生成测试的java类和配置文件,不需要手动去配置。

相关推荐
難釋懷1 分钟前
StringRedisTemplate
java·spring boot·spring
Swift社区10 分钟前
Java 实战 - 字符编码问题解决方案
java·开发语言
灰灰勇闯IT10 分钟前
【Flutter for OpenHarmony--Dart 入门日记】第3篇:基础数据类型全解析——String、数字与布尔值
android·java·开发语言
tobias.b13 分钟前
408真题解析-2010-10-数据结构-快速排序
java·数据结构·算法·计算机考研·408真题解析
季明洵13 分钟前
力扣反转链表、两两交换链表中的节点、删除链表的倒数第N个节点
java·算法·leetcode·链表
猿小羽16 分钟前
Java 架构演进史:从咖啡杯到云原生霸主
java·云原生·架构
chilavert31816 分钟前
技术演进中的开发沉思-330 : 虚拟机命令行工具
java·jvm
Java程序员威哥18 分钟前
使用Java自动加载OpenCV来调用YOLO模型检测
java·开发语言·人工智能·python·opencv·yolo·c#
小北方城市网25 分钟前
Spring Cloud Gateway实战:路由、限流、熔断与鉴权全解析
java·spring boot·后端·spring·mybatis
ZealSinger31 分钟前
Nacos2.x 事件驱动架构:原理与实战
java·spring boot·spring·spring cloud·nacos·架构·事件驱动