简体   繁体   English

SpringBoot中具有多个测试类的H2数据库

[英]H2 database with Multiple Test Classes in SpringBoot

In my SpringBoot application, I have one test classes inside /src/test/java .在我的 SpringBoot 应用程序中,我在/src/test/java中有一个测试类。

For Testing (Unit Tests).用于测试(单元测试)。 I want to use the In memory H2 database.我想使用 In memory H2 数据库。 I have the following Database Url我有以下数据库网址

jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/schema.sql'\\;runscript from 'classpath:/data.sql'

So when I run the test.所以当我运行测试时。 the database is created and the scripts ( schema.sql and data.sql ) runs correctly as expected.数据库已创建并且脚本( schema.sqldata.sql )按预期正确运行。 it creates some tables and puts some test data over there.它创建了一些表并将一些测试数据放在那里。

Now the problem is I added another Test class and written some tests there.现在的问题是我添加了另一个测试类并在那里编写了一些测试。 so whats happening now is, first test class runs succesfully, but when the second class loads, it tries to run the scripts ( schema.sql and data.sql ) again on the in memory H2 database.所以现在发生的事情是,第一个测试类成功运行,但是当第二个类加载时,它会尝试在内存 H2 数据库上再次运行脚本( schema.sqldata.sql )。 and that obviously fails.这显然失败了。 because those tables are already there in the DB.因为这些表已经存在于数据库中。

Can anyone please suggest how Can i achieve the behaviour I want.谁能建议我如何实现我想要的行为。 such that my scripts should run only once and then all the test classes should use that same database.这样我的脚本应该只运行一次,然后所有的测试类都应该使用同一个数据库。

My Test class example is below我的测试类示例如下

@RunWith(SpringRunner.class)
@SpringBootTest()
public class CreateServiceTest {

    @Autowired
    private CreateRepo repo;
    
    @Test
    public void testCreation(){
        // test code here    
    }

With spring boot the h2 database can be defined uniquely for each test.使用 spring boot,可以为每个测试唯一地定义 h2 数据库。 Just override the data source URL for each test只需覆盖每个测试的数据源 URL

@SpringBootTest(properties = {"spring.config.name=myapp-test-h2","myapp.trx.datasource.url=jdbc:h2:mem:trxServiceStatus"}) @SpringBootTest(属性 = {"spring.config.name=myapp-test-h2","myapp.trx.datasource.url=jdbc:h2:mem:trxServiceStatus"})

The tests can run in parallel.测试可以并行运行。

refer: https://stackoverflow.com/a/49644877参考: https ://stackoverflow.com/a/49644877

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM