Sub topic 15
Testing with profiles and property overrides
This chapter shows how to run tests against a chosen profile and how to override single properties for one test. It assumes you have read the earlier chapters on property precedence, @ConfigurationProperties, validation and @Profile beans. It reuses the MailProperties record and the Notifier beans from those chapters.
What a test needs from configuration
A Spring Boot test starts a real application context, so it reads application.yaml like production does. Tests usually need three adjustments:
- Select a profile, so the right files and beans are used.
- Override one or two values, such as a port or sender address.
- Supply values that are only known at runtime, such as a container's mapped port.
Spring's test framework covers each case with a different annotation. They all feed the same property-source precedence you already know, placed above files and environment variables.
Selecting profiles with @ActiveProfiles
@ActiveProfiles tells the test context which profiles are active. This test activates prod and overrides one property inline:
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;
import org.springframework.test.context.ActiveProfiles;
@SpringBootTest(properties = "app.mail.port=2525")
@ActiveProfiles("prod")
class MailPropertiesTest {
@Autowired
MailProperties mail;
@Test
void usesProdHostAndTestPort() {
assertThat(mail.host()).isEqualTo("smtp.example.com");
assertThat(mail.port()).isEqualTo(2525);
}
}The host comes from the prod document in application.yaml. The port comes from the properties attribute, which beats every file.
@ActiveProfiles has the same effect on the other profile features:
application-prod.yamlandon-profile: proddocuments are loaded.@Profile("prod")beans are registered.- Profile groups expand.
@ActiveProfiles("prod")also activatesproddbandprodmqif the group from the earlier chapter is configured.
You can check the bean selection directly:
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;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ActiveProfiles;
class NotifierSelectionTest {
@SpringBootTest
static class DefaultProfile {
@Autowired ApplicationContext context;
@Test
void usesLoggingNotifier() {
assertThat(context.containsBean("loggingNotifier")).isTrue();
assertThat(context.containsBean("emailNotifier")).isFalse();
}
}
@SpringBootTest
@ActiveProfiles("prod")
static class ProdProfile {
@Autowired ApplicationContext context;
@Test
void usesEmailNotifier() {
assertThat(context.containsBean("emailNotifier")).isTrue();
assertThat(context.containsBean("loggingNotifier")).isFalse();
}
}
}Static nested classes are not discovered by default in JUnit 5 unless they are annotated with @Nested, and @Nested requires non-static inner classes. In a real project, put each class in its own file so the build runs both.
Overriding values for one test
Three annotations override properties. They differ in scope and in how late the value can be computed.
| Mechanism | Where it goes | Use it when |
|---|---|---|
| `@SpringBootTest(properties = ...)` | On the test class | You need one or two inline values. |
| `@TestPropertySource` | On the test class | You want inline values or a whole test-only properties file. |
| `@DynamicPropertySource` | On a static method | The value is computed at runtime, for example a container port. |
@TestPropertySource
@TestPropertySource accepts inline properties and a list of locations:
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;
import org.springframework.test.context.TestPropertySource;
@SpringBootTest
@TestPropertySource(properties = {
"[email protected]",
"app.mail.retry-attempts=1"
})
class MailSenderOverrideTest {
@Autowired
MailProperties mail;
@Test
void usesOverriddenValues() {
assertThat(mail.sender()).isEqualTo("[email protected]");
assertThat(mail.retryAttempts()).isEqualTo(1);
}
}Relaxed binding applies, so app.mail.retry-attempts binds to the retryAttempts component.
@DynamicPropertySource
Some values do not exist when the annotations are read. A throwaway SMTP server started by the test is one example. @DynamicPropertySource registers suppliers that are called when the context is built:
import static org.assertj.core.api.Assertions.assertThat;
import java.net.ServerSocket;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@SpringBootTest
class FreePortMailTest {
static final ServerSocket SERVER = open();
static ServerSocket open() {
try {
return new ServerSocket(0);
} catch (java.io.IOException e) {
throw new IllegalStateException(e);
}
}
@DynamicPropertySource
static void mailProperties(DynamicPropertyRegistry registry) {
registry.add("app.mail.port", SERVER::getLocalPort);
}
@AfterAll
static void close() throws Exception {
SERVER.close();
}
@Autowired
MailProperties mail;
@Test
void bindsPortChosenAtRuntime() {
assertThat(mail.port()).isEqualTo(SERVER.getLocalPort());
}
}The method must be static and take a DynamicPropertyRegistry. Container libraries such as Testcontainers use the same pattern for database URLs.
Which override wins
Test sources sit near the top of the precedence list. From highest to lowest:
@DynamicPropertySourcevalues.@TestPropertySourceproperties.- The
propertiesattribute of@SpringBootTest. - Command-line arguments passed to the test application.
- Environment variables and system properties.
- Profile-specific files, then
application.yaml.
If two overrides in one test set the same key, use this order to predict the result.
Test-only configuration files
There are two ways to keep test settings in a file. They behave very differently.
If you add src/test/resources/application.yaml, it shadows src/main/resources/application.yaml. Both are classpath:/application.yaml, and the test classes directory comes first on the classpath. Boot loads only the first one, so every default from your main file disappears.
The safer approach is a profile-specific file. Create src/test/resources/application-test.yaml with only the values that differ, and activate it with @ActiveProfiles("test"). It is loaded on top of the main application.yaml, so the main defaults remain.
Testing property binding without the full application
A @SpringBootTest starts everything, which is slow for checking one properties class. ApplicationContextRunner builds a small context from only what you list. It is a good fit for validation rules, because each case gives a fresh context:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class MailPropertiesValidationTest {
@EnableConfigurationProperties(MailProperties.class)
static class Config {
}
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(Config.class);
@Test
void bindsValidValuesAndAppliesDefault() {
runner.withPropertyValues(
"app.mail.host=localhost",
"app.mail.port=1025",
"[email protected]")
.run(context -> {
assertThat(context).hasNotFailed();
assertThat(context.getBean(MailProperties.class).retryAttempts())
.isEqualTo(3);
});
}
@Test
void rejectsPortZero() {
runner.withPropertyValues(
"app.mail.host=localhost",
"app.mail.port=0",
"[email protected]")
.run(context -> assertThat(context).hasFailed());
}
}The second test shows the fail-fast rule from the validation chapter. A bad port stops the context from starting, and the runner reports that as a failed context instead of throwing.
Common errors
- Profile has no effect. The test class has
@ActiveProfiles("prod")but the file is namedapplication-production.yaml. The file suffix must equal the profile name. - Missing defaults in tests. A test-resources
application.yamlshadows the main one, as described above. - Slow test suite. Spring caches contexts by their configuration. Every distinct combination of profiles and test properties creates a new context. Group tests that share settings, and avoid
@DirtiesContextunless the test really changes shared state. - Dynamic value ignored. A
@DynamicPropertySourcemethod that is notstaticis rejected. A value read into a field before the method runs will also be stale. - Profile bleed.
@ActiveProfilesis inherited by subclasses by default. SetinheritProfiles = falsewhen a subclass needs a different set.
Exercise
Exercise
A test class has @SpringBootTest(properties = "app.mail.port=2525") and @TestPropertySource(properties = "app.mail.port=3025"). Nothing else sets the port. What does MailProperties.port() return, and what happens if you add a @DynamicPropertySource that registers app.mail.port as 4025?
Show answer
It returns 3025, because @TestPropertySource ranks above the properties attribute of @SpringBootTest. With the @DynamicPropertySource added, it returns 4025, because dynamic properties have the highest precedence of the three.
Exercise
You add src/test/resources/application.yaml containing only app.mail.sender: [email protected]. Tests now fail because app.mail.host is blank. Why, and how do you fix it without losing the sender override?
Show answer
The test file shadows src/main/resources/application.yaml, so the main file, including app.mail.host, is never loaded. Rename the test file to application-test.yaml and add @ActiveProfiles("test") to the tests. The main file is then loaded, and the test profile file overrides only the sender.