Search code examples
javaspringspring-boottddintegration-testing

How to load h2 data in spring boot test before component initialization


I have a @Component with @Scheduled method which runs every x mins (fixed delay) While running my integration @SpringBootTest, this component gets initialized with application context, and then executes my test methods

The scheduler polls DB periodically and executes some logic. So as soon as application-context is loaded, it requires data pre-loaded in h2 database

@Component
public class MyScheduler {
   ...
   ...
    @Scheduled(fixedDelayString = "${poll.interval:300}")
    public void testXYZ() throws Exception {
        dbService.fetchRecords();
        //do blah blah
    }
}

How can I pre-load initial data in h2 before @SpringBootTest application-context is loaded ?

I want to perform data assertions based on few @Scheduled periodic runs once the service comes up in my integration test

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MyIntegrationTest{

    ...

    @Test
    @Sql(scripts={"classpath:data/data.sql"}, 
    config=@SqlConfig(transactionMode = TransactionMode.ISOLATED), 
    executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
    testMySchedulerLogic() {
        assertTrue(isProcessed(), true);
    }
}

Solution

  • Create import.sql file in test resources with the data you need.

    In addition, a file named import.sql in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the ddl-auto property is set to create or create-drop). This can be useful for demos and for testing if you are careful but is probably not something you want to be on the classpath in production. It is a Hibernate feature (and has nothing to do with Spring).

    Source: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html