【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

戳上方蓝字“Java知音”关注我

快速测试mybatis的sql

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

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

【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

由于需要启动spring,当项目较大的时候启动速度很慢,有些项目的启动时间超过30秒。导致测试sql速度很慢,尤其项目上不允许引入热部署jrebel,改下sql重新再测试等很花时间。

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

【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

配置文件

【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

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

速度非常快 如下:

【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

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

生成testcase支持PageHelper分页插件

修改setUp方法加入interceptor即可

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.classbuilder.openSession(true));

生成testcase支持mybatisplus

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

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

在test类可以修改setUpMybatisDatabase 如下

@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.classbuilder.openSession(true));
}

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

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

https://plugins.jetbrains.com/plugin/9837-mybatiscodehelperpro

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

【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

来源:juejin.cn/post/7271942371638214708

后端专属技术群

构建高质量的技术交流社群,欢迎从事编程开发、技术招聘HR进群,也欢迎大家分享自己公司的内推信息,相互帮助,一起进步!

文明发言,以交流技术职位内推行业探讨为主

广告人士勿入,切勿轻信私聊,防止被骗

【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

加我好友,拉你进群

【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

原文始发于微信公众号(Java知音):【冷门但实用的小技巧】快速测试 Mybatis 复杂SQL,无需启动 Spring

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/292889.html

(0)
Java知音的头像Java知音bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!