Reputation: 6360
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?
Upvotes: 3
Views: 366
Reputation: 315
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
Upvotes: 3