I have seen projects where a standalone application.properties
is defined under src/test/resources
containing all the properties from the default application.properties
defined under src/main/resources
while overriding properties for testing purposes. The disadvantage of this approach is that every change (adding/removing/updating of properties) must be done in both application.properties, otherwise tests may fail.
On the other hand I have seen projects where only a context based property file is defined under src/test/resources
, say application-test.properties
containing only the overriden properties for testing purposes. This approach merges the default application.properties
under src/main/resources
and the application-test.properties
under src/test/resources
. The respective context must be activated in test classes via @ActiveProfiles
, say @ActiveProfiles("test")
What is the approach you follow and why? Is there any best practice or recommendation for this?
Thanks for your replies in advance.
CodePudding user response:
spring.profiles.active=dev
add this config in application.properties file
CodePudding user response:
Profiles are generally used to "map" different Spring beans accordingly. I've seen that people usually stick to three of them for most of the workflows: development
, test
, and production
— mainly in tutorials and blogs.
I use profiles aligned with the actual environments the application is going to be deployed at since it's more realistic. So I always run the tests with the local
profile. If I need any specific settings for running the tests, I just redefine an application.yaml
file under src/test/resources
and overwrite what's needed.
In this way, you would always effectively have what's going to be used to run the application in each environment within src/main/resources
, and if anything needs to be overwritten only for testing, the YAML file in src/test/resources
could take care of that.
For instance, let's say your src/main/resources/application.yaml
file looks like:
application:
key: value-common
spring:
profiles:
active: default
sql:
init:
encoding: UTF-8
---
spring:
config:
activate:
on-profile: local
main:
banner-mode: console
---
spring:
config:
activate:
on-profile: test
This defines effectively two profiles: local
and test
— because default
would have what's common to both. Now, if you place an application.yaml
file with the following content in src/test/resources
:
application:
key: value-for-testing-only
spring:
profiles:
active: default
---
spring:
config:
activate:
on-profile: local
---
spring:
config:
activate:
on-profile: test
...everything will stay the same, but application.key
will be bound to value-for-testing-only
instead when you run the tests (for any profile). If you happen to just run the application, it will be bound to value-common
instead.