I need to change the quarkus application properties in unit tests to check some negative use cases.
application.properties:
myapp.prop = oldValue
The corresponding property class:
@ConfigMapping(prefix = "myapp")
public interface MyPropertiesMapping {
String prop();
}
I tried to set the system property in @BeforeAll
method and got different results for @ConfigProperty
field and @ConfigMapping
field.
JUnit test:
@QuarkusTest
class ConfigTest {
@ConfigProperty(name = "myapp.prop")
String property;
@Inject
MyPropertiesMapping myProperites;
@BeforeAll
static void changeProperty() {
System.setProperty("myapp.prop", "newValue");
}
@AfterAll
static void clearProperty() {
System.clearProperty("myapp.prop");
}
@Test
void testConfigProperty() {
Assertions.assertEquals("newValue", property);
}
@Test
void testConfigMapping() {
Assertions.assertEquals("oldValue", myProperites.prop());
}
The test shows that property
field is set to newValue, but myProperties.prop()
still shows oldValue.
So there are 2 questions:
@ConfigProperty
and @ConfigMapping
is different in the case?@ConfigMapping
attributes properly?The difference is that @ConfigMapping
it is initialized globally before test classes are executed, and @ConfigProperty
injection is local, after the test class is evaluated (since you need the instance to be able to inject it).
If you need to change the configuration for a test, my recommendation is to use @TestProfile
and override the configuration with public Map<String, String> getConfigOverrides()
instead of setting it up via SystemProperties
. If the configuration set via SystemProperties
is not cleaned correctly, it may leak to other test classes.
Check: https://quarkus.io/guides/getting-started-testing#testing_different_profiles