3

I have an Spring Boot application integrated with Hibernate for the database persistence.

I have two different data.sql files:

  • One in src/main/resources for database initialization
  • One in src/test/resources for testing purposes

While testing, both of them are loaded before any test class. However, I only want to load the test/resources one, leaving the main/resources only and solely for app initialization.

How can I do that?

Thanks.

Alberto Castaño
  • 186
  • 5
  • 16

4 Answers4

0

You should change the spring.jpa.hibernate.ddl-auto=create to update (it only updates the changes from the .sql file), because with create each time that the app runs, "cleans the DB", so thats why the both .sql are processed each time.

I hope this solve your problem.

  • No! Maybe I did not explain myself good enough. What I want is to actually create the database from scratch everytime I run my tests, but only from test/resources/data.sql, not from main/resources/data.sql. Right now both of them are being invoked – Alberto Castaño Jul 16 '18 at 10:26
  • As @Rahul said, you can't stop loading the main/resources .sql file. Because is needed for the app to run. – Ramon jansen gomez Jul 16 '18 at 10:34
0

if test class is starting the spring boot application then i don`t think that you can stop loading the main/resources .sql file.

but if you want to load the .sql file from test/resources just before/after the execution of methods(in test class) then you can use @SqlGroup annotation.

@SqlGroup({
    @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:beforeTestRun.sql"),
    @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:afterTestRun.sql")

          })
Rahul Baghaniya
  • 291
  • 4
  • 5
0

You can add the following configuration (at least in spring boot 2) to your test application.yaml or application.properties file.

spring:
  datasource:
    data: data.sql

Once this value is set spring boot will only load the test data.sql when running tests.

Grant
  • 258
  • 2
  • 8
-1

Maintain a separate properties file for test as it will help you in segregating the things between test and development.

application.properties for dev
application-local.properties for local env
application-test.properties for test 

Have profiles according to your need and have properties with respect to profiles.

Another alternative is to override the properties based on your need.

TechGuy
  • 1
  • 1