Reputation: 211
I have created a spring boot application and have been using the H2 embedded database. Which is working fine.
However, I added the application.properties
file and added the dependency to postgresql. This also works fine, but when I have to test my application I want to start it using the embedded DB. I don't see any other way of doing it except by removing the application.properties
file, which is not a very neat way of doing it.
I was hoping that the flag spring.datasource.initialization-mode=embedded
will make it load the embedded DB, but it is completely ignoring it.
Is there a way of achieving this by just turning a flag on and off?
I am using gradle as a build tool. If it's possible to achieve this via gradle, that would be nice.
Upvotes: 1
Views: 572
Reputation: 1938
In addition to what @Isank said, this might be useful in the cases when you want to run the application (not unit/integration tests, but maybe manually test it) using an in-memory database or just a different database.
You can define profiles, and for each profile you can have different application properties. Using the naming convention, let's say you have three environments (dev, prod, test), you define three different properties files:
application-dev.properties
application-prod.properties
application-test.properties
You need to put all these files in src/main/resources/
so that they get picket up automatically. Alternatively, you need to tell spring-boot where the properties files are by passing the runtime argument --spring.config.location
.
Now, having all these files how do you tell spring-boot which one to use?
If your properties files are named according to the convention application-{profile}.properties
, then you do it by passing the --spring.profiles.active={profile}
argument.
jar
filejava -jar spring-boo-app-name.jar --spring.profiles.active=prod
//this will use the application-prod.properties file
bootRun
gradle taskbootRun {
args '--spring.profiles.active=prod'
}
When you start your spring-boot app, you will see in the console the active profile.
Upvotes: 2
Reputation: 1675
You don't need any flag or any kind of toggling in this case. The application.properties
that resides inside src/main/resources
affect the application and the one inside src/test/resources
affects the tests of that application.
Now, as you said you want to use an embedded DB for your tests all you need to use is @DataJpaTest
on your test class.
@DataJpaTest
provides some standard setup needed for testing the persistence layer:
And, this is how your repository test will look like
@RunWith(SpringRunner.class)
@DataJpaTest
public class SomeRepositoryIntegrationTest {}
@Autowired
private SomeRepository repository;
// write test cases here
}
You can find a detailed tutorial on this topic here
Upvotes: 1