Test profiles let you run your Spring Boot app with special settings just for testing. This helps keep tests separate from real app settings.
0
0
Test profiles and configuration in Spring Boot
Introduction
You want to use a different database for testing than for real use.
You need to change some app settings only when running tests.
You want to avoid sending real emails during tests.
You want to speed up tests by disabling slow features.
You want to isolate test data from production data.
Syntax
Spring Boot
spring.profiles.active=test
# application-test.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.hibernate.ddl-auto=create-dropUse
spring.profiles.active to select which profile to run.Create separate
application-{profile}.properties files for each profile.Examples
This sets the active profile to dev and changes logging level only for that profile.
Spring Boot
# application.properties spring.profiles.active=dev # application-dev.properties logging.level.root=DEBUG
This annotation tells Spring Boot to use the test profile when running this test class.
Spring Boot
@ActiveProfiles("test") @SpringBootTest public class MyServiceTest { }
Overrides mail server settings only for the test profile to avoid sending real emails.
Spring Boot
# application-test.properties spring.mail.host=localhost spring.mail.port=2525
Sample Program
This Spring Boot app returns a message from configuration. When run with the test profile active, it shows the test message. Otherwise, it shows the default message.
Spring Boot
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class ProfileController { @Value("${app.message}") private String message; @GetMapping("/message") public String getMessage() { return message; } } // application.properties // app.message=Hello from default profile // application-test.properties // app.message=Hello from test profile
OutputSuccess
Important Notes
Activate profiles in application.properties or via command line with --spring.profiles.active=test.
Use @ActiveProfiles in tests to specify which profile to use.
Keep test configurations simple and isolated to avoid affecting real app behavior.
Summary
Test profiles let you run your app with special settings just for tests.
Use application-{profile}.properties files to separate settings.
Activate profiles via config files, command line, or annotations in tests.