Search code examples
javajunitjunit5

Properly set (system) properties in JUnit 5


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, so that other tests do not inadvertently depend on possible side effects.

Since JUnit 5 is released, I wonder if there is a "JUnit 5 way" of doing this?


Solution

  • 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 and set, respectively, the values of system properties for a test execution. Both annotations work on the test method and class level, are repeatable, combinable, and inherited from higher-level containers. After the annotated method has been executed, the properties mentioned in the annotation will be restored to their original value or the value of the higher-level container, 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"));
    }
    

    If you don't know your values at compile time and/or want to parameterize a system properties test, you can use @RestoreSystemProperties (since v2.1.0). From the docs:

    @RestoreSystemProperties can be used to restore changes to system properties made directly in code. While @ClearSystemProperty and @SetSystemProperty set or clear specific properties and values, they don’t allow property values to be calculated or parameterized, thus there are times you may want to directly set properties in your test code. @RestoreSystemProperties can be placed on test methods or test classes and will completely restore all system properties to their original state after a test or test class is complete.

    Example:

    @ParameterizedTest
    @ValueSource(strings = { "new value", "newer value" })
    @RestoreSystemProperties
    void parameterizedTest(String value) {
        System.setProperty("some key", value);
        // ...
    }