pagehelper-spring-boot
pagehelper-spring-boot copied to clipboard
springboot启动分页正常,单元测试无法分页
环境:pagehelper 1.1.1, spring boot 1.5.3 , mysql5.7 mybatis-spring-boot-test-autoconfigure 使用mybatis generator, 生成domain,example,mapper,编写service; 在@SpringBootApplication主入口程序的 @Override public void run(String... arg0) throws Exception { 中调用分页service方法,日志打印正常分页,证明包引入和配置无误;
然而在单元测试中,发现没有limit和count注入sql, mapper查询方法返回的list无法cast成page对象,仍是ArrayList。 测试代码如下:
@Import(xxServiceImpl.class) public class xxServiceImplTest {
@Autowired
private xxService service;
@Test
public void testFindPageByExample() throws Exception {
Domain domain1 = createDomain();
@SuppressWarnings("unused")
Domain domain2 = createDomain();
DomainExample example = new DomainExample();
example.setOrderByClause("ext_id");
example.createCriteria().andDelFlagEqualTo(false);
Pagi<Domain> pagi = service.findPageByExample(1, 1, example);
assertEquals(1, pagi.getPageData().size());
assertTrue(pagi.getPageData().contains(domain1));
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
@Import(MyTestsConfiguration.class)
public class MyTests {
@Test
public void exampleTest() {
...
}
}
测试参考 spring boot 文档写法: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

PageHelper 在单元测试中不生效。
springBoot: 2.3.1.RELEASE
implementation "org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3" testImplementation "org.mybatis.spring.boot:mybatis-spring-boot-starter-test:2.1.3" implementation group: 'com.github.pagehelper', name: 'pagehelper-spring-boot-starter', version: '1.3.0'
请帮忙看下什么问题,谢谢 @abel533
咱们的情况正好相反,我反而是在单元测试中可以正常分页,在启动的时候反而无法分页了。。。。
我的问题解决了,是多数据源的时候缺了配置,中间 bean.setPlugins(new Interceptor[]{new PageInterceptor()});
这一句是关键:
@Bean
public SqlSessionTemplate sqlSessionTemplateForIntegration() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSourceForIntegration);
bean.setPlugins(new Interceptor[]{new PageInterceptor()});
return new SqlSessionTemplate(Objects.requireNonNull(bean.getObject()));
}
大哥,有没有更好的分页插件推荐啊,这个不怎么更新,而且依赖太重了,想换一个。