px06 px06 - 4 months ago 26
SQL Question

Initialising a database before Spring Boot test

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
})

Answer

The above answers all use the .sql schema loading technique where I'd have to have a .sql schema for tests. I didn't want to do it that way as my schema would be expanding and I'd rather not go through the hassle of adding entries to the schema as my tests expand.

As I'm using Spring Boot, I came across this annotation which seems to solve the issue by first running bootRun and then running the tests.

In my test annotations I replaced the @ContextConfigurations with @SpringApplicationConfiguration and left all the classes to be the same. This seemed to solve the issue. So now the test task invokes bootRun to load the classes and then runs the tests.

See @SpringApplicationConfiguration

Hop this helps anyone facing the same issue.

Comments