[英]H2 database with Multiple Test Classes in SpringBoot
在我的 SpringBoot 应用程序中,我在/src/test/java
中有一个测试类。
用于测试(单元测试)。 我想使用 In memory H2 数据库。 我有以下数据库网址
jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/schema.sql'\\;runscript from 'classpath:/data.sql'
所以当我运行测试时。 数据库已创建并且脚本( schema.sql
和data.sql
)按预期正确运行。 它创建了一些表并将一些测试数据放在那里。
现在的问题是我添加了另一个测试类并在那里编写了一些测试。 所以现在发生的事情是,第一个测试类成功运行,但是当第二个类加载时,它会尝试在内存 H2 数据库上再次运行脚本( schema.sql
和data.sql
)。 这显然失败了。 因为这些表已经存在于数据库中。
谁能建议我如何实现我想要的行为。 这样我的脚本应该只运行一次,然后所有的测试类都应该使用同一个数据库。
我的测试类示例如下
@RunWith(SpringRunner.class)
@SpringBootTest()
public class CreateServiceTest {
@Autowired
private CreateRepo repo;
@Test
public void testCreation(){
// test code here
}
使用 spring boot,可以为每个测试唯一地定义 h2 数据库。 只需覆盖每个测试的数据源 URL
@SpringBootTest(属性 = {"spring.config.name=myapp-test-h2","myapp.trx.datasource.url=jdbc:h2:mem:trxServiceStatus"})
测试可以并行运行。
参考: https ://stackoverflow.com/a/49644877
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.