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