我正在 Spring Boot 中開發一個應用程式。我使用 PostreSQL 資料庫進行生產,我希望我的 JUnit 5 測驗在 H2 記憶體資料庫上運行。問題是,經過一些配置,測驗似乎仍然沒有在記憶體資料庫上運行:
我可以從 prod db 訪問物體(保存的物體不會保留在 prod db 中)
如果我通過測驗日志 grep,我可以看到 Hibernate 使用 org.hibernate.dialect.PostgreSQLDialect
@DataJpaTest
@SpringBootTest
@TestPropertySource(locations = "classpath:application-test.properties")
@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
public class ClinicTest {
@Resource
private ClinicRepository clinicRepository;
@Test
public void givenClinic_whenSave_thenGetOk() {
var clinic = new Clinic();
clinic.setName("asd asd");
clinic.setShortName("asd");
// the ids of prod db entities are printed
clinicRepository.findAll().forEach(clinic1 -> System.out.println(clinic1.getId()));
// the id keeps incrementing between runs
System.out.println(clinicRepository.save(clinic).getId());
}
}
應用程式-test.properties
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:testdb
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create-drop
spring.test.database.replace=none
我應該改變什么才能在記憶體資料庫中的 H2 上運行獨立測驗?
uj5u.com熱心網友回復:
默認情況下,Spring 會為測驗創建一個 H2 DB。您無需在屬性檔案中指定它。
只需在 pom.xml 中添加 h2 并將其范圍設定為測驗。Spring Boot 應該處理剩下的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/473588.html
