简体   繁体   中英

H2 database with Multiple Test Classes in SpringBoot

In my SpringBoot application, I have one test classes inside /src/test/java .

For Testing (Unit Tests). I want to use the In memory H2 database. 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. 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. 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. Just override the data source URL for each test

@SpringBootTest(properties = {"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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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