快速测试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类和配置文件,不需要手动去配置。

相关推荐
vx-程序开发16 小时前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea
艾莉丝努力练剑17 小时前
【QT:解决问题】Qt5Core.dll:无法定位程序输入点
java·开发语言·qt·学习·面试
小蒜学长17 小时前
“喵汪联盟”宠物领养系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·宠物
程序员黑豆17 小时前
Java字符串常量池完全指南:原理、intern()方法与性能优化最佳实践
java·前端·ai编程
AI人工智能+电脑小能手17 小时前
大白话说Java设计模式-14-适配器模式(业务实战篇)
java·设计模式·适配器模式·系统兼容·多渠道对接
xbgRS20 小时前
springboot的自动装配
java·spring boot
嘻哈∠※1 天前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
白狐_7981 天前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
zander2581 天前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界
java·数据结构·算法
码匠许师傅1 天前
【C++ 面试真题】聊聊 C++ 的拷贝构造与拷贝赋值
java·c++·面试