We are using an approach similar to System Rules to handle (system) properties in our JUnit 4 tests. The main reason for this is to clean up the environment after each test,
There is JUnit Pioneer, a "JUnit 5 extension pack". It comes with @ClearSystemProperty
and @SetSystemProperty
. From the docs:
The
@ClearSystemProperty
and@SetSystemProperty
annotations can be used to clear, respectively, set the values of system properties for a test execution. Both annotations work on the test method and class level, are repeatable as well as combinable. After the annotated method has been executed, the properties mentioned in the annotation will be restored to their original value or will be cleared if they didn't have one before. Other system properties that are changed during the test, are not restored.
Example:
@Test
@ClearSystemProperty(key = "some key")
@SetSystemProperty(key = "another key", value = "new value")
void test() {
assertNull(System.getProperty("some key"));
assertEquals("new value", System.getProperty("another key"));
}