在Junit5中使用H2作为测试DB
我正在春季启动中开发一个应用程序。我使用PosttreesQL DB进行生产,我希望我的Junit 5测试能够在H2内存DB上进行。问题是,经过一些配置后,测试似乎仍然无法在内存db上运行:
i可以从prod db访问实体(一个保存的实体在prod db tho中不持续)
如果我在测试日志中抓取了hibernate usg.hibernate.dialect.postgresqlesclesclesect
@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());
}
}
application-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上运行独立测试吗?
I'm developing an app in Spring Boot. I use a PostreSQL DB for production, and I want my JUnit 5 tests to run on a H2 memory DB. Problem is, after some configuration, the tests still don't seem to run on the in-memory db:
I can access entities from the prod db (a saved entity doesn't persist in the prod db tho)
if I grep through the test logs, I can see that Hibernate uses 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());
}
}
application-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
What should I change to run self-contained test on a H2 in memory database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,Spring为测试创建了H2 DB。您无需在属性文件中指定它。
只需在pom.xml中添加H2并将其范围设置为测试即可。春季靴子应处理其余的。
Spring, by default, creates an H2 DB for the test. You don't need to specify it in your properties file.
Just add h2 in your pom.xml and set its scope to test. Spring Boot should handle the rest.
您的application-test.propties没有用户和pasword
尝试添加此信息:
Your application-test.proprties does not have user and pasword
try adding this: