快速测试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 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir1 小时前
Calendar类日期设置进位问题
java·开发语言
季鸢3 小时前
Java设计模式之状态模式详解
java·设计模式·状态模式
@yanyu6663 小时前
springboot实现查询学生
java·spring boot·后端
ascarl20103 小时前
准确--k8s cgroup问题排查
java·开发语言
magic 2453 小时前
Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误
java
爱敲代码的憨仔4 小时前
分布式协同自动化办公系统-工作流引擎-流程设计
java·flowable·oa
纪元A梦4 小时前
分布式拜占庭容错算法——PBFT算法深度解析
java·分布式·算法
卿着飞翔4 小时前
RabbitMQ入门4.1.0版本(基于java、SpringBoot操作)
java·rabbitmq·java-rabbitmq
陈阿土i4 小时前
SpringAI 1.0.0 正式版——利用Redis存储会话(ChatMemory)
java·redis·ai·springai