Unit Testing Configuration Properties and Profiles
Overview
This skill provides patterns for unit testing @ConfigurationProperties bindings, environment-specific configurations, and property validation using JUnit 5. Covers testing property name mapping, type conversions, validation constraints, nested structures, and profile-specific configurations without full Spring context startup.
Key validation checkpoints:
- Property prefix matches between
@ConfigurationProperties and test properties
- Validation triggers on
@Validated classes with invalid values
- Type conversions work for Duration, DataSize, collections, and maps
When to Use
- Testing
@ConfigurationProperties property binding
- Testing property name mapping and type conversions
- Validating configuration with
@NotBlank, @Min, @Max, @Email constraints
- Testing environment-specific configurations (dev, prod)
- Testing nested property structures and collections
- Verifying default values when properties are not specified
- Fast configuration tests without Spring context startup
Instructions
- Set up test dependencies: Add
spring-boot-starter-test and AssertJ dependencies
- Use ApplicationContextRunner: Test property bindings without starting full Spring context
- Define property prefixes: Ensure
@ConfigurationProperties(prefix = "...") matches test property paths
- Test all property paths: Verify each property including nested structures and collections
- Test validation constraints: Use
context.hasFailed() to verify @Validated properties reject invalid values
- Test type conversions: Verify Duration (
30s), DataSize (50MB), collections, and maps convert correctly
- Test default values: Verify properties have correct defaults when not specified in test properties
- Test profile-specific configs: Use
@Profile with ApplicationContextRunner for environment-specific configurations
- Test edge cases: Include empty strings, null values, and type mismatches
Troubleshooting flow:
- If properties don't bind → Check prefix matches (kebab-case to camelCase conversion)
- If validation doesn't trigger → Verify
@Validated annotation is present
- If context fails to start → Check dependencies and
@ConfigurationProperties class structure
Examples
Setup: Test Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
Basic Pattern: Property Binding
@ConfigurationProperties(prefix = "app.security")
@Data
public class SecurityProperties {
private String jwtSecret;
private long jwtExpirationMs;
private int maxLoginAttempts;
private boolean enableTwoFactor;
}
class SecurityPropertiesTest {
@Test
void shouldBindPropertiesFromEnvironment() {
new ApplicationContextRunner()
.withPropertyValues(
"app.security.jwtSecret=my-secret-key",
"app.security.jwtExpirationMs=3600000",
"app.security.maxLoginAttempts=5",
"app.security.enableTwoFactor=true"
)
.withBean(SecurityProperties.class)
.run(context -> {
SecurityProperties props = context.getBean(SecurityProperties.class);
assertThat(props.getJwtSecret()).isEqualTo("my-secret-key");
assertThat(props.getJwtExpirationMs()).isEqualTo(3600000L);
assertThat(props.getMaxLoginAttempts()).isEqualTo(5);
assertThat(props.isEnableTwoFactor()).isTrue();
});
}
@Test
void shouldUseDefaultValuesWhenPropertiesNotProvided() {
new ApplicationContextRunner()
.withPropertyValues("app.security.jwtSecret=key")
.withBean(SecurityProperties.class)
.run(context -> {
SecurityProperties props = context.getBean(SecurityProperties.class);
assertThat(props.getJwtSecret()).isEqualTo("key");
assertThat(props.getMaxLoginAttempts()).isZero();
});
}
}
Validation Testing
@ConfigurationProperties(prefix = "app.server")
@Data
@Validated
public class ServerProperties {
@NotBlank
private String host;
@Min(1)
@Max(65535)
private int port = 8080;
@Positive
private int threadPoolSize;
}
class ConfigurationValidationTest {
@Test
void shouldFailValidationWhenHostIsBlank() {
new ApplicationContextRunner()
.withPropertyValues(
"app.server.host=",
"app.server.port=8080",
"app.server.threadPoolSize=10"
)
.withBean(ServerProperties.class)
.run(context -> {
assertThat(context).hasFailed()
.getFailure()
.hasMessageContaining("host");
});
}
@Test
void shouldPassValidationWithValidConfiguration() {
new ApplicationContextRunner()
.withPropertyValues(
"app.server.host=localhost",
"app.server.port=8080",
"app.server.threadPoolSize=10"
)
.withBean(ServerProperties.class)
.run(context -> {
assertThat(context).hasNotFailed();
assertThat(context.getBean(ServerProperties.class).getHost()).isEqualTo("localhost");
});
}
}
Type Conversion Testing
@ConfigurationProperties(prefix = "app.features")
@Data
public class FeatureProperties {
private Duration cacheExpiry = Duration.ofMinutes(10);
private DataSize maxUploadSize = DataSize.ofMegabytes(100);
private List<String> enabledFeatures;
private Map<String, String> featureFlags;
}
class TypeConversionTest {
@Test
void shouldConvertDurationFromString() {
new ApplicationContextRunner()
.withPropertyValues("app.features.cacheExpiry=30s")
.withBean(FeatureProperties.class)
.run(context -> {
assertThat(context.getBean(FeatureProperties.class).getCacheExpiry())
.isEqualTo(Duration.ofSeconds(30));
});
}
@Test
void shouldConvertCommaDelimitedList() {
new ApplicationContextRunner()
.withPropertyValues("app.features.enabledFeatures=feature1,feature2")
.withBean(FeatureProperties.class)
.run(context -> {
assertThat(context.getBean(FeatureProperties.class).getEnabledFeatures())
.containsExactly("feature1", "feature2");
});
}
}
For nested properties, profile-specific configurations, collection binding, and advanced validation patterns, see references/advanced-examples.md.
Best Practices
- Test all property bindings including nested structures and collections
- Test validation constraints for all
@NotBlank, @Min, @Max, @Email, @Positive annotations
- Test both default and custom values to verify fallback behavior
- Use ApplicationContextRunner for fast context-free testing
- Test profile-specific configurations separately with
@Profile
- Verify type conversions for Duration, DataSize, collections, and maps
- Test edge cases: empty strings, null values, type mismatches, out-of-range values
Constraints and Warnings
- Kebab-case to camelCase: Property
app.my-property maps to myProperty in Java
- Loose binding: Spring Boot uses loose binding by default; use strict binding if needed
@Validated required: Add @Validated annotation to enable constraint validation
@ConstructorBinding: All parameters must be bindable when using constructor binding
- List indexing: Use
[0], [1] notation; ensure sequential indexing for lists
- Duration format: Accepts ISO-8601 (
PT30S) or simple syntax (30s, 1m, 2h)
- Context isolation: Each
ApplicationContextRunner creates a new context with no shared state
- Profile activation: Use
spring.profiles.active=profileName in withPropertyValues() for profile tests
Troubleshooting
| Issue |
Cause |
Solution |
| Properties not binding |
Prefix mismatch |
Verify @ConfigurationProperties(prefix="...") matches property paths |
| Validation not triggered |
Missing @Validated |
Add @Validated annotation to configuration class |
| Context fails to start |
Missing dependencies |
Ensure spring-boot-starter-test is in test scope |
| Nested properties null |
Inner class missing |
Use @Data on nested classes or provide getters/setters |
| Collection binding fails |
Wrong indexing |
Use [0], [1] notation, not (0), (1) |
1---
2name: unit-test-config-properties
3description: Provides patterns for unit testing `@ConfigurationProperties` classes with `@ConfigurationPropertiesTest`. Validates property binding, tests validation constraints, verifies default values, checks type conversions, and mocks property sources for Spring Boot configuration properties. Use when testing application configuration binding, validating YAML or application.properties files, verifying environment-specific settings, or testing nested property structures.
4allowed-tools: Read, Write, Bash, Glob, Grep
5metadata:
6 source: https://skillmd.com/skills/giuseppe-trisciuoglio/unit-test-config-properties
7---
8
9# Unit Testing Configuration Properties and Profiles
10
11## Overview
12
13This skill provides patterns for unit testing `@ConfigurationProperties` bindings, environment-specific configurations, and property validation using JUnit 5. Covers testing property name mapping, type conversions, validation constraints, nested structures, and profile-specific configurations without full Spring context startup.
14
15**Key validation checkpoints:**
16- Property prefix matches between `@ConfigurationProperties` and test properties
17- Validation triggers on `@Validated` classes with invalid values
18- Type conversions work for Duration, DataSize, collections, and maps
19
20## When to Use
21
22- Testing `@ConfigurationProperties` property binding
23- Testing property name mapping and type conversions
24- Validating configuration with `@NotBlank`, `@Min`, `@Max`, `@Email` constraints
25- Testing environment-specific configurations (dev, prod)
26- Testing nested property structures and collections
27- Verifying default values when properties are not specified
28- Fast configuration tests without Spring context startup
29
30## Instructions
31
321. **Set up test dependencies**: Add `spring-boot-starter-test` and AssertJ dependencies
332. **Use ApplicationContextRunner**: Test property bindings without starting full Spring context
343. **Define property prefixes**: Ensure `@ConfigurationProperties(prefix = "...")` matches test property paths
354. **Test all property paths**: Verify each property including nested structures and collections
365. **Test validation constraints**: Use `context.hasFailed()` to verify `@Validated` properties reject invalid values
376. **Test type conversions**: Verify Duration (`30s`), DataSize (`50MB`), collections, and maps convert correctly
387. **Test default values**: Verify properties have correct defaults when not specified in test properties
398. **Test profile-specific configs**: Use `@Profile` with `ApplicationContextRunner` for environment-specific configurations
409. **Test edge cases**: Include empty strings, null values, and type mismatches
41
42**Troubleshooting flow:**
43- If properties don't bind → Check prefix matches (kebab-case to camelCase conversion)
44- If validation doesn't trigger → Verify `@Validated` annotation is present
45- If context fails to start → Check dependencies and `@ConfigurationProperties` class structure
46
47## Examples
48
49### Setup: Test Dependencies
50
51```xml
52<dependency>
53 <groupId>org.springframework.boot</groupId>
54 <artifactId>spring-boot-configuration-processor</artifactId>
55 <scope>provided</scope>
56</dependency>
57<dependency>
58 <groupId>org.springframework.boot</groupId>
59 <artifactId>spring-boot-starter-test</artifactId>
60 <scope>test</scope>
61</dependency>
62<dependency>
63 <groupId>org.assertj</groupId>
64 <artifactId>assertj-core</artifactId>
65 <scope>test</scope>
66</dependency>
67```
68
69### Basic Pattern: Property Binding
70
71```java
72@ConfigurationProperties(prefix = "app.security")
73@Data
74public class SecurityProperties {
75 private String jwtSecret;
76 private long jwtExpirationMs;
77 private int maxLoginAttempts;
78 private boolean enableTwoFactor;
79}
80
81class SecurityPropertiesTest {
82
83 @Test
84 void shouldBindPropertiesFromEnvironment() {
85 new ApplicationContextRunner()
86 .withPropertyValues(
87 "app.security.jwtSecret=my-secret-key",
88 "app.security.jwtExpirationMs=3600000",
89 "app.security.maxLoginAttempts=5",
90 "app.security.enableTwoFactor=true"
91 )
92 .withBean(SecurityProperties.class)
93 .run(context -> {
94 SecurityProperties props = context.getBean(SecurityProperties.class);
95 assertThat(props.getJwtSecret()).isEqualTo("my-secret-key");
96 assertThat(props.getJwtExpirationMs()).isEqualTo(3600000L);
97 assertThat(props.getMaxLoginAttempts()).isEqualTo(5);
98 assertThat(props.isEnableTwoFactor()).isTrue();
99 });
100 }
101
102 @Test
103 void shouldUseDefaultValuesWhenPropertiesNotProvided() {
104 new ApplicationContextRunner()
105 .withPropertyValues("app.security.jwtSecret=key")
106 .withBean(SecurityProperties.class)
107 .run(context -> {
108 SecurityProperties props = context.getBean(SecurityProperties.class);
109 assertThat(props.getJwtSecret()).isEqualTo("key");
110 assertThat(props.getMaxLoginAttempts()).isZero();
111 });
112 }
113}
114```
115
116### Validation Testing
117
118```java
119@ConfigurationProperties(prefix = "app.server")
120@Data
121@Validated
122public class ServerProperties {
123 @NotBlank
124 private String host;
125
126 @Min(1)
127 @Max(65535)
128 private int port = 8080;
129
130 @Positive
131 private int threadPoolSize;
132}
133
134class ConfigurationValidationTest {
135
136 @Test
137 void shouldFailValidationWhenHostIsBlank() {
138 new ApplicationContextRunner()
139 .withPropertyValues(
140 "app.server.host=",
141 "app.server.port=8080",
142 "app.server.threadPoolSize=10"
143 )
144 .withBean(ServerProperties.class)
145 .run(context -> {
146 assertThat(context).hasFailed()
147 .getFailure()
148 .hasMessageContaining("host");
149 });
150 }
151
152 @Test
153 void shouldPassValidationWithValidConfiguration() {
154 new ApplicationContextRunner()
155 .withPropertyValues(
156 "app.server.host=localhost",
157 "app.server.port=8080",
158 "app.server.threadPoolSize=10"
159 )
160 .withBean(ServerProperties.class)
161 .run(context -> {
162 assertThat(context).hasNotFailed();
163 assertThat(context.getBean(ServerProperties.class).getHost()).isEqualTo("localhost");
164 });
165 }
166}
167```
168
169### Type Conversion Testing
170
171```java
172@ConfigurationProperties(prefix = "app.features")
173@Data
174public class FeatureProperties {
175 private Duration cacheExpiry = Duration.ofMinutes(10);
176 private DataSize maxUploadSize = DataSize.ofMegabytes(100);
177 private List<String> enabledFeatures;
178 private Map<String, String> featureFlags;
179}
180
181class TypeConversionTest {
182
183 @Test
184 void shouldConvertDurationFromString() {
185 new ApplicationContextRunner()
186 .withPropertyValues("app.features.cacheExpiry=30s")
187 .withBean(FeatureProperties.class)
188 .run(context -> {
189 assertThat(context.getBean(FeatureProperties.class).getCacheExpiry())
190 .isEqualTo(Duration.ofSeconds(30));
191 });
192 }
193
194 @Test
195 void shouldConvertCommaDelimitedList() {
196 new ApplicationContextRunner()
197 .withPropertyValues("app.features.enabledFeatures=feature1,feature2")
198 .withBean(FeatureProperties.class)
199 .run(context -> {
200 assertThat(context.getBean(FeatureProperties.class).getEnabledFeatures())
201 .containsExactly("feature1", "feature2");
202 });
203 }
204}
205```
206
207For **nested properties**, **profile-specific configurations**, **collection binding**, and **advanced validation patterns**, see `references/advanced-examples.md`.
208
209## Best Practices
210
211- **Test all property bindings** including nested structures and collections
212- **Test validation constraints** for all `@NotBlank`, `@Min`, `@Max`, `@Email`, `@Positive` annotations
213- **Test both default and custom values** to verify fallback behavior
214- **Use ApplicationContextRunner** for fast context-free testing
215- **Test profile-specific configurations** separately with `@Profile`
216- **Verify type conversions** for Duration, DataSize, collections, and maps
217- **Test edge cases**: empty strings, null values, type mismatches, out-of-range values
218
219## Constraints and Warnings
220
221- **Kebab-case to camelCase**: Property `app.my-property` maps to `myProperty` in Java
222- **Loose binding**: Spring Boot uses loose binding by default; use strict binding if needed
223- **`@Validated` required**: Add `@Validated` annotation to enable constraint validation
224- **`@ConstructorBinding`**: All parameters must be bindable when using constructor binding
225- **List indexing**: Use `[0]`, `[1]` notation; ensure sequential indexing for lists
226- **Duration format**: Accepts ISO-8601 (`PT30S`) or simple syntax (`30s`, `1m`, `2h`)
227- **Context isolation**: Each `ApplicationContextRunner` creates a new context with no shared state
228- **Profile activation**: Use `spring.profiles.active=profileName` in `withPropertyValues()` for profile tests
229
230## Troubleshooting
231
232| Issue | Cause | Solution |
233|-------|-------|----------|
234| Properties not binding | Prefix mismatch | Verify `@ConfigurationProperties(prefix="...")` matches property paths |
235| Validation not triggered | Missing `@Validated` | Add `@Validated` annotation to configuration class |
236| Context fails to start | Missing dependencies | Ensure `spring-boot-starter-test` is in test scope |
237| Nested properties null | Inner class missing | Use `@Data` on nested classes or provide getters/setters |
238| Collection binding fails | Wrong indexing | Use `[0]`, `[1]` notation, not `(0)`, `(1)` |