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

相关推荐
高斯林.神犇12 分钟前
idea快捷键
java·ide·intellij-idea
青春易逝丶31 分钟前
术语缩写
java
ideal-cs38 分钟前
总结:Nginx配置文件案例说明
java·运维·nginx·nginx配置文件
无尽的沉默1 小时前
Thymeleaf 基本语法和表达式
java·开发语言
Coder_Boy_1 小时前
Java后端核心技术体系全解析(个人总结)
java·开发语言·spring boot·分布式·spring cloud·中间件
南部余额1 小时前
函数式接口 Lambda 表达式好搭档:Predicate、Function、Consumer、Supplier
java·开发语言·consumer·lambda·function·predicate·supplier
Java后端的Ai之路2 小时前
【JDK】-JDK 17 新特性整理(比较全)
java·开发语言·后端·jdk17
小小小米粒2 小时前
Spring Boot Starter ,不止是 “打包好配置的工具类包”
java·开发语言
用户8307196840822 小时前
告别冗余!Spring Boot Web 入参转换 6 种玩法,@InitBinder 可以退休了
java·spring boot
Desirediscipline2 小时前
#include<limits>#include <string>#include <sstream>#include <iomanip>
java·开发语言·前端·javascript·算法