Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising a database before Spring Boot test

Tags:

I'm using JUnit to test my application and everything works fine as long as the database has been initialised before the testing (using gradle bootRun to run as a web-app). However, if the database is empty, the application does not seem to initialise any models or entities before testing. Is there a way I'm supposed to do this? I made an assumption that the ApplicationRunner class will be ran before the test and initalise the entities. Is there a way to do this or am I using the wrong approach?

This is how my application.properties file is looking like:

server.port=8090 server.ssl.key-store=classpath:keystore.jks server.ssl.key-store-password=123456 server.ssl.key-password 123456 spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect spring.jpa.hibernate.ddl-auto=create spring.jpa.hibernate.naming-strategy:org.hibernate.cfg.ImprovedNamingStrategy application.logger.org.springframework=INFO 

My database is stored in /src/main/java/application/persistence/DbConfig.java using a DriverManagerDataSource connection. And I have setup ApplicationRunner to run add a few rows to the db upon starting.

edit:

I should also add that these are the annotations I'm using on the JUnit test file:

@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes={     AdeyTrackApplication.class,      SecurityConfig.class,      WebConfig.class,     AuthorizationController.class     }) 
like image 407
px06 Avatar asked Jul 08 '16 08:07

px06


1 Answers

There are various options if you do not want to execute that explicitly from @Before JUnit hook.

  1. Use Spring Boot's JDBC initialization feature, where you would place schema.sql or data.sql into src/test/resources folder, so that it would be picked up only during testing.
  2. Use Spring's @Sql annotation
like image 98
luboskrnac Avatar answered Nov 13 '22 06:11

luboskrnac