Spring Boot Test 是否可以根据 Activity 配置文件设置 sql 脚本的条件执行? 我的意思是,我对带有一些 @sql 注释的存储库进行了集成测试,例如:
@Sql(scripts = "/scripts/entity_test_clear.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
对于配置文件 h2 我想执行 entity_test_clear.sql
对于配置文件mysql,我想执行entity_test_clear_mysql.sql
原因是我对这些数据库使用了不同的语法,尤其是这个数据库:
ALTER TABLE organization ALTER COLUMN org_id RESTART WITH 1;
ALTER TABLE 组织 AUTO_INCREMENT = 1;
Mysql 不理解语法 #1,而 h2 不理解语法 #2(尽管设置了 mysql 模式,如 MODE=MYSQL)
默认情况下,我使用 h2 进行 IT 测试,但在极少数情况下,我也想检查 mysql 是否也能顺利运行。
P.S 我当然可以尝试使用 @Profile
的直接解决方案,并为 h2 和 mysql 的每个测试硬编码两个副本,但它与测试中的大量代码重复相结合,我想避免。
已编辑: 测试用例如下所示:
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class EntityRepositoryTestIT {
@Autowired
private EntityRepository entityRepository;
@Test
@Sql(scripts = {"/scripts/entity_test_data.sql", "/scripts/entity_test_data_many.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/scripts/entity_test_clear.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void findTest() {
Page<Entity> e = entityRepository.findBySomeDetails(1L, PageRequest.of(0, 20));
Assert.assertEquals(3, e.getContent().size());
Assert.assertEquals(1, e.getContent().get(0).getResources().size());
// more asserts
}
感谢您的任何建议!
最佳答案
在对问题进行更深入的研究之后,我最终找到了这个简单的解决方法。
@Sql(scripts = "/scripts/entity_test_clear.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
对于scripts参数,要求是编译时常量。您不能简单地从 application.properties 获取当前配置文件值并将其替换为运行正确的脚本名称。
在执行正确脚本的 ScriptUtils 中引入 @After 和 @Before 方法相当冗长,事实上,对我不起作用(在脚本执行过程中发生了一些卡住)。
所以我所做的只是引入一个具有单个常量的类:
/**
* Constant holder for exceptionally database IT testing purposes
* for switching between h2 and mysql
*/
public class ActiveProfile {
/**
* Current profile for database IT tests.
* Make sure the value is equal to the value of
* <i>spring.profiles.active</i> property from test application.properties
*/
public static final String NOW = "h2";
}
然后@sql行变成:
@Sql(scripts = "/scripts/test_data_clear_"+ ActiveProfile.NOW+".sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
要使用另一个数据库进行测试 (mysql),我只需要 1) 更改 application.properties 中的当前 spring.profiles.active=mysql 配置文件和 2) 将此常量更改为 mysql;
这并不意味着成为模范解决方案,只是一种简单有效的解决方法。
关于java - Spring 启动测试 : execute different sql scripts in tests depending on the active profile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52077711/