我试图根据Spring测试环境中的活动概要文件(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());
}
}启用调试的org.springframework.jdbc上的记录器显示,在调用此行时会发生冻结:
ALTER TABLE entity AUTO_INCREMENT = 1;这仅在MySql中失败,而对于H2则很好:
ALTER TABLE entity ALTER COLUMN id RESTART WITH 1;通过使用注释,MySql ONLY的测试再次正常运行:
@Sql(scripts = "/scripts/test_data_clear_mysql.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)看起来@sql注释比编程调用ScriptUtils增加了更多的逻辑。使用H2,ScriptUtils和@sql注释都能顺利地工作。
问题是注释不允许执行的sql脚本的动态更改,它的“脚本”参数是编译时间常数。
任何关于如何使它工作的建议将是非常感谢的!
发布于 2019-02-20 23:04:52
我的直觉是,您根本没有正确地关闭/返回数据库连接。
@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块中,以便关闭连接(如果使用数据库池(例如Hikari),则返回到池中)。
https://stackoverflow.com/questions/52129294
复制相似问题