One off configuration for a @SpringBootTest Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of One off configuration for a @SpringBootTest without wasting too much if your time.

The question is published on by Tutorial Guruji team.

How can I bootstrap my Spring Boot 2 integration tests so that across all of them I can have one set of configurations which pre-seeds the test database with some test data that can be used across all integration tests?

Answer

Supposing you are using h2 test database.

My src/test/resources/application.properties file has:

spring.jpa.hibernate.ddl-auto=create-drop

You’ll need a configuration file with the following structure. (This is a configuration example located inside the folder src/test/java):

@Profile("test")
@Configuration
public class H2Config {

    @Autowired
    private DataSource datasource;

    @PostConstruct
    public void loadSQL() throws Exception {
        ScriptUtils.executeSqlScript(datasource.getConnection(), new ClassPathResource("/sql/load_database.sql"));
    }
}

The file ‘load_database.sql’: (the full path is /src/test/resources/sql/load_database.sql)

CREATE OR REPLACE TABLE OPER_DISPN(
    ID          NUMBER NOT NULL,
    DT_VCTO_OPER  DATE         NOT NULL
);


INSERT INTO OPER_DISPN(ID,DT_VCTO_OPER) VALUES (1,TO_DATE('2018/09/21', 'yyyy/mm/dd')); 

If you are using mapped entities(with @Entity) ( with create-drop) you won’t need the ‘CREATE TABLE’ part for that.

And now, all your integration tests have the script data inserted

Edit: ( My test structure) I’ve created at github my example application. Please see the test structure and run the tests:

TNotMappedRepository.testLoadDataFind()
PersonRepository.testLoadDataFind()

Github: https://github.com/thiagochagas/insert-data-tests

We are here to answer your question about One off configuration for a @SpringBootTest - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji