我正在尝试根据 Spring Boot 测试环境中的 Activity 配置文件(h2 或 mysql)执行不同的 sql 脚本。这是我尝试使用 MySql 执行的导致卡住的测试用例:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class EntityRepositoryTestIT {
@Autowired
EntityRepository entityRepository;
@Autowired
private DataSource dataSource;
@Value("${spring.profiles.active}")
private String profile;
@After
public void after() throws Exception {
ScriptUtils.executeSqlScript(dataSource.getConnection(),
new ClassPathResource("/scripts/test_data_clear_"+profile+".sql"));
}
@Test
@Sql(scripts = "/scripts/test_data.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
public void findAllTest() throws Exception {
Assert.assertEquals(7, entityRepository.findAll().size());
}
}
启用 DEBUG 的 org.springframework.jdbc 上的记录器显示在调用此行时发生卡住:
ALTER TABLE entity AUTO_INCREMENT = 1;
这仅在 MySql 上失败,而在 H2 上工作正常:
ALTER TABLE entity ALTER COLUMN id RESTART WITH 1;
测试在 MySql 上再次正常工作仅通过使用注释:
@Sql(scripts = "/scripts/test_data_clear_mysql.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@sql 注释似乎比 ScriptUtils 的编程调用添加了更多逻辑。使用 H2,ScriptUtils 和 @sql 注释都可以顺利工作。
问题是注释不允许动态更改执行的 sql 脚本,它的 'scripts' 参数是一个编译时间常量。
任何有关如何使其工作的建议将不胜感激!
最佳答案
我的直觉是您根本没有正确关闭/返回数据库连接。
@After
public void after() throws Exception {
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
ScriptUtils.executeSqlScript(connection,
new ClassPathResource("/scripts/test_data_clear_"+profile+".sql"));
log.info("SQL script successful");
} else {
log.warn("!!! No connection available !!!");
}
}
}
即将您的连接包装在 try-catch-resources
block 中,以便关闭连接(如果您使用的是数据库池,则返回到池中,例如 Hikari)。
关于java - Spring ScriptUtils : with MySql causes tests to freeze forever,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52129294/