Annotation Type RestoreEnvironmentVariables


  • @Retention(RUNTIME)
    @Target({METHOD,TYPE})
    @Inherited
    @ExtendWith(EnvironmentVariableExtension.class)
    public @interface RestoreEnvironmentVariables
    @RestoreEnvironmentVariables is a JUnit Jupiter extension to restore the entire set of environment variables to the original value, or the value of the higher-level container, after the annotated element has been executed.

    Use this annotation when you need programmatically modify environment variables in a test method or in @BeforeAll / @BeforeEach blocks. To simply set or clear an environment variable, consider @SetEnvironmentVariable or @ClearEnvironmentVariable instead.

    RestoreEnvironmentVariables can be used on the method and on the class level. When placed on a test method, environment variables are stored before the method is run and restored after the method is complete. Specifically, variables are stored after any @BeforeAll methods have run and before any @BeforeEach methods.

    When placed on a test class, environment variables are stored before the test class runs and restored after the test class is complete, in addition to running before and after each test method just as if the annotation was on each method. An advanced usage could include modifying some environment variables in a @BeforeAll block to apply to all tests and additional variable modifications within some tests themselves, all while safely restoring the state of the environment variables after each test and after the entire test class.

    WARNING: Java considers environment variables to be immutable, so this extension uses reflection to change them. This requires that the SecurityManager allows modifications and can potentially break on different operating systems and Java versions. Be aware that this is a fragile solution and consider finding a better one for your specific situation. If you're running on Java 9 or later and are encountering warnings or errors, check the documentation.

    SetEnvironmentVariable and ClearEnvironmentVariable interaction: During parallel test execution, all tests annotated with RestoreEnvironmentVariables, SetEnvironmentVariable, ReadsEnvironmentVariable, and WritesEnvironmentVariable are scheduled in a way that guarantees correctness under mutation of shared global state.

    For more details and examples, see the documentation on @ClearEnvironmentVariable, @SetEnvironmentVariable, and @RestoreEnvironmentVariables.

    Since:
    2.0.0