Sub topic 5
Profiles, test properties, and @TestConfiguration
This chapter assumes you know how @SpringBootTest loads a context, how Spring profiles and application.properties work in a running application, and how @Bean methods and @Primary behave. It shows how to change configuration and beans for a test without touching production code.
Why tests need their own configuration
Production configuration often points at things a test must not touch: a real clock, a payment gateway URL, a shared database. Spring Boot gives you three tools for this:
- Properties set only for tests.
- Profiles that switch on test-specific files and beans.
- Extra beans declared in test code with
@TestConfiguration.
Each tool changes the context that Spring builds for the test. Use the smallest one that solves your problem.
The example application
The examples use a service that reads a property and a Clock bean.
import java.time.Clock;
import java.time.LocalTime;
import java.time.ZoneOffset;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class GreetingService {
private final Clock clock;
private final String prefix;
public GreetingService(Clock clock, @Value("${greeting.prefix:Hello}") String prefix) {
this.clock = clock;
this.prefix = prefix;
}
public String greetingFor(String name) {
int hour = LocalTime.now(clock.withZone(ZoneOffset.UTC)).getHour();
String period = hour < 12 ? "morning" : "afternoon";
return prefix + ", " + name + " (" + period + ")";
}
}import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ClockConfig {
@Bean
Clock clock() {
return Clock.systemUTC();
}
}Setting properties for one test class
Spring Boot offers several ways to set properties in a test. They differ in scope and in precedence.
| Mechanism | Where it applies | Typical use |
|---|---|---|
| `@SpringBootTest(properties = ...)` | One test class | One or two inline values |
| `@TestPropertySource` | One test class | Inline values or a whole properties file |
| `@DynamicPropertySource` | One test class | Values known only at runtime, such as a container port |
| `src/test/resources/application-<profile>.properties` | Any test that activates the profile | A shared set of test settings |
When the same key is set in several places, the higher source in this list wins:
@TestPropertySource@DynamicPropertySource- The
propertiesattribute of@SpringBootTest - Command-line arguments, system properties, and environment variables
- Config files such as
application.properties
So a value from @TestPropertySource overrides the same key in @SpringBootTest(properties = ...).
Inline properties
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(properties = "greeting.prefix=Good day")
class InlinePropertyTest {
@Autowired
GreetingService service;
@Test
void usesTestPrefix() {
assertThat(service.greetingFor("Ada")).startsWith("Good day, Ada");
}
}A properties file with @TestPropertySource
@TestPropertySource can load a file from the classpath. Use it when several keys belong together.
import org.springframework.test.context.TestPropertySource;
@SpringBootTest
@TestPropertySource(locations = "classpath:greeting-test.properties",
properties = "greeting.prefix=Howdy")
class FilePropertyTest {
// inline "properties" win over the same key in the file
}Runtime values with @DynamicPropertySource
Some values exist only after the test starts, such as a mapped port of a container or a mock server. @DynamicPropertySource takes a static method that registers suppliers. Spring calls each supplier when it first needs the value.
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@SpringBootTest
class DynamicPropertyTest {
static final int PORT = 18080; // in practice, taken from a started server or container
@DynamicPropertySource
static void registerProperties(DynamicPropertyRegistry registry) {
registry.add("payment.base-url", () -> "http://localhost:" + PORT);
}
}The method must be static. For Testcontainers databases, the later chapter on containers shows @ServiceConnection, which replaces most hand-written dynamic properties.
Profiles in tests
A profile lets you keep a set of test settings in one file and switch it on by name. Create src/test/resources/application-test.properties:
greeting.prefix=Test
spring.jpa.show-sql=true
logging.level.org.springframework.web=DEBUGThen activate the profile with @ActiveProfiles:
import org.springframework.test.context.ActiveProfiles;
@SpringBootTest
@ActiveProfiles("test")
class ProfileTest {
@Autowired
GreetingService service;
@Test
void readsProfileFile() {
assertThat(service.greetingFor("Ada")).startsWith("Test, Ada");
}
}Beans marked @Profile("test") are also created only when that profile is active. Keep such beans rare. A production class that behaves differently under a test profile means the tests no longer exercise the code that ships.
Adding and replacing beans with @TestConfiguration
@TestConfiguration marks a class that adds beans to the test context. It differs from @Configuration in two ways:
- Component scanning skips it, so it never leaks into other tests or into production.
- It adds to the application's configuration. It does not replace it.
Here is a fixed Clock, so the greeting does not depend on the time the test runs.
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
@TestConfiguration(proxyBeanMethods = false)
public class FixedClockConfig {
@Bean
@Primary
Clock fixedClock() {
return Clock.fixed(Instant.parse("2026-01-15T08:30:00Z"), ZoneOffset.UTC);
}
}A top-level @TestConfiguration must be imported explicitly:
import org.springframework.context.annotation.Import;
@SpringBootTest
@Import(FixedClockConfig.class)
class FixedClockTest {
@Autowired
GreetingService service;
@Test
void greetsInTheMorning() {
assertThat(service.greetingFor("Ada")).isEqualTo("Hello, Ada (morning)");
}
}Two clock beans now exist, clock and fixedClock. @Primary makes fixedClock win wherever a single Clock is injected.
Nested configuration
A static nested class annotated with @TestConfiguration is picked up automatically by the enclosing test. No @Import is needed.
@SpringBootTest
class NestedConfigTest {
@TestConfiguration(proxyBeanMethods = false)
static class Config {
@Bean
@Primary
Clock fixedClock() {
return Clock.fixed(Instant.parse("2026-01-15T15:00:00Z"), ZoneOffset.UTC);
}
}
@Autowired
GreetingService service;
@Test
void greetsInTheAfternoon() {
assertThat(service.greetingFor("Ada")).isEqualTo("Hello, Ada (afternoon)");
}
}Replacing a bean by name
Spring Boot rejects two bean definitions with the same name. If you give the test bean the same name as the production bean, startup fails with a BeanDefinitionOverrideException. You have two choices:
- Use a different name and
@Primary, as above. This is the safer choice, because nothing is silently replaced. - Set
spring.main.allow-bean-definition-overriding=truein the test, then declare a bean with the same name. This works, but it also hides accidental duplicates, so use it sparingly.
To replace a bean with a Mockito mock instead, use @MockitoBean, covered in the chapter on mocking beans.
Choosing a mechanism
Cost: every variation is a new context
Spring caches an application context and reuses it across test classes that have the same configuration. The cache key includes the active profiles, the property sources, the imported configuration classes, and the mock beans. Two classes that differ in one inline property each build their own context. A suite with many one-off combinations spends most of its time starting contexts.
To keep reuse high:
- Share one profile file across classes instead of writing a different
propertiesattribute in each. - Put common overrides in one shared
@TestConfigurationand import it everywhere. - Prefer a plain unit test when a class under test does not need Spring at all.
The chapter on the test context cache explains the key in detail.
Common errors
- Profile file ignored. The file name must match the profile exactly,
application-test.propertiesfor@ActiveProfiles("test"), and it must be on the test classpath. - Nested configuration not applied. The nested class must be
static, and it must be annotated@TestConfiguration. NoUniqueBeanDefinitionException. You added a second bean of the same type without@Primary.@DynamicPropertySourcefails. The method is notstatic, or its parameter is not aDynamicPropertyRegistry.
Exercise
A test class is annotated with @SpringBootTest(properties = "app.mode=a") and @TestPropertySource(properties = "app.mode=b"). What value does app.mode have in the test, and why? What happens to the context cache if a second class uses only @SpringBootTest(properties = "app.mode=a")?
Show answer
The value is b, because @TestPropertySource has higher precedence than the properties attribute of @SpringBootTest. The second class has a different set of property sources, so it gets a different cache key and Spring starts a second application context for it.