On my spring boot application I want to override just one of my @Configuration
classes with a test configuration (in particular my @EnableAuthorizationServer
@Configuration
class), on all of my tests.
So far after an overview of spring boot testing features and spring integration testing features no straightforward solution has surfaced:
@TestConfiguration
: It's for extending, not overriding;@ContextConfiguration(classes=…)
and@SpringApplicationConfiguration(classes =…)
lets me override the whole config, not just the one class;- An inner
@Configuration
class inside a@Test
is suggested to override the default configuration, but no example is provided;
Any suggestions?
You should use spring boot profiles:
@Profile("test")
.@Profile("production")
.spring.profiles.active=production
.@Profile("test")
.So when your application starts it will use "production" class and when test stars it will use "test" class.
If you use inner/nested
@Configuration
class it will be be used instead of a your application’s primary configuration.Inner test configuration
Example of an inner @Configuration for your test:
Reusable test configuration
If you wish to reuse the Test Configuration for multiple tests, you may define a standalone Configuration class with a Spring Profile
@Profile("test")
. Then, have your test class activate the profile with@ActiveProfiles("test")
. See complete code:@Primary
The
@Primary
annotation on the bean definition is to ensure that this one will have priority if more than one are found.I recently had to create a dev version of our application, that should run with
dev
active profile out of the box without any command line args. I solved it with adding this one class as a new entry, which sets the active profile programmatically:See Spring Boot Profiles Example by Arvind Rai for more details.