Spring Boot Test 是否可以根據活動配置文件設置 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 organisation ALTER COLUMN org_id RESTART WITH 1;ALTER TABLE organisation AUTO_INCREMENT = 1;Mysql 不理解語法 #1,而 h2 不理解語法 #2(盡管設置了 mysql 模式,如 MODE=MYSQL)默認情況下,我使用 h2 進行 IT 測試,但在一些罕見的情況下,我也想檢查一切是否與 mysql 一起順利運行。PS我當然可以嘗試一個直接的解決方案,@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}感謝您的任何建議!
2 回答

慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
您可以將 @Profile 注釋與單獨的類一起使用,每個類都用于每個 DMBS,將公共邏輯放在另一個類中以避免代碼重復。您正在使用 Spring,因此您可以使用以下內容來獲取它。
@Profile("mysql")
@Sql(scripts="... my mysql scripts...")
public class MySqlTests{
@Autowired
private CommonTestsLogic commonLogic;
@Test
public void mySqlTest1(){
commonlogic.test1();
}
}
@Profile("oracle")
@Sql(scripts="... my oracle scripts...")
public class MyOracleTests{
@Autowired
private CommonTestsLogic commonLogic;
@Test
public void myOracleTest1(){
commonlogic.test1();
}
}
添加回答
舉報
0/150
提交
取消