How to better use multiple Spring boot profiles in testing

Deepti Mittal
2 min readNov 27, 2021
Springboot

In spring boot application we can define multiple profiles to allow different values for properties. This is mainly used to define environment details for multiple deployment environments.

More details on spring boot profiles can we found at: https://docs.spring.io/spring-boot/docs/1.2.0.M1/reference/html/boot-features-profiles.html

Apart than environment details feature toggles, performance related configurations which might vary based for dev, performance and production environments are also good to define in spring profiles.

Spring has good documentation on how to define multiple profiles hence not detailing here and above link should help in understanding this.

Defining spring profiles for different environments is a common practice in spring boot project but when we used it for unit/component tests helped us in faster execution of tests.

We actually used to have component level tests.

Component tests: These are one level higher of unit tests where you will test the functionality within the boundary of one component or microservice. If microservice is using Kafka or other database you would also spin mock of that to test integration paths. How to do component level testing with Kafka have been covered at: https://deeptimittalblogger.medium.com/using-spring-for-kafka-integration-tests-1202ec6d6fbd

Disadvantage of these test cases is slowness to spin embedded services and close it, so if you have 2–3 tests your time for feedback is going to be much higher if you are running them sequentially. JUnit5 provides way of executing test cases in parallel and that definitely helped in faster execution.

To achieve this we defined one test case per JUnit class and defined specific profile for it. This ensures every test case has its own Kafka running and does not interfere with any other test cases.

If you are defining 15 properties in spring profile, most of them are going to be same and port where you start Kafka or other service os going to be different. Spring boot does not provide any straight way where you can ask one profile to use configurations from other profile and just override few.

To solve that in test cases itself we need to define sequence in which profiles should be applied and profiles defined later will take precedence and will override defined values for previous profile.

This helped in reducing lot of duplications across profile files.

Example for it can be found at:

--

--

Deepti Mittal

I am working as software engineer in Bangalore for over a decade. Love to solve core technical problem and then blog about it.