DataJpaTest搭配MySQL全文搜索测试失效问题排查
问题:MySQL全文检索Repository方法测试返回空结果
待测试的Repository方法
@Query(value = "select * from table " + "where match(name_column) AGAINST(:name in BOOLEAN MODE)", nativeQuery = true) List<ManagedGroup> findByGroupNameMatches(@Param("name") String groupName);
测试代码
@Test public void findByGroupNameMatches_should_return_when_contains_part_of_name(){ ManagedGroup managedGroup = prepearGroup(UUID.randomUUID().toString()); managedGroup.setGroupName("def123"); testEntityManager.persistAndFlush(managedGroup); // 尝试通过Repository保存 groupRepository.save(managedGroup); // 可查询到两个分组:'def123'和'default name' List<ManagedGroup> res = groupRepository.findAll(); Pageable pageable = new OffsetLimitPageRequest(0, 10, Sort.by(Sort.Direction.DESC, "id")); List<ManagedGroup> managedGroupPage = groupRepository.findByGroupNameMatches("+def*"); // 调用方法后managedGroupPage为空 Assertions.assertEquals(defaultManagedGroup, managedGroupPage.get(0)); }
问题详情
- 测试失败,
findByGroupNameMatches返回空结果 - 尝试用
jdbcTemplate保存并查询实体,仍无结果 - 其他测试正常,排除通用配置问题
- 该方法在业务控制器及QA环境中可正常运行,通过了QA测试
- 连接QA数据库测试时,能查询到测试启动前持久化的实体,但测试过程中新增的实体无法被搜索到
- 已尝试多种flush组合,问题仍未解决
测试环境配置
MySQL容器配置
static final MySQLContainer DATABASE = new MySQLContainer("mysql:8.0.23"); static { DATABASE.start(); } static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { public void initialize(ConfigurableApplicationContext context) { TestPropertyValues.of( "spring.datasource.url=" + DATABASE.getJdbcUrl(), "spring.datasource.username=" + DATABASE.getUsername(), "spring.datasource.password=" + DATABASE.getPassword() ).applyTo(context.getEnvironment()); } }
测试类注解
@DataJpaTest @ExtendWith(SpringExtension.class) @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @DisabledIfEnvironmentVariable(named = "RUN_INTEGRATION_TEST", matches = "false") @DirtiesContext
内容的提问来源于stack exchange,提问作者Yolomiys
相关产品推荐
相关产品推荐

