1. Overview

System properties live in a global, shared map on the JVM. When a test sets a property with System.setProperty(), that change persists for the entire test run unless the test explicitly restores the original value. This can lead to subtle test pollution: a passing test can silently corrupt state, causing a completely unrelated test to fail and resulting in flaky behavior.

In this article, we’ll explore a JUnit extension that helps us manage system properties declaratively and avoid flaky tests. We’ll start with @SetSystemProperty and @ClearSystemProperty, which are helpful for setting or removing properties for individual tests or test classes. Finally, we’ll discover @RestoreSystemProperties and use it to restore all system properties set during a specific test or class.

2. Setting and Clearing Properties

Let’s imagine a simple use case where one test needs a special system property, say “app.mode” to be set to “debug“. A common pattern is to use the java.lang.System‘s API to set the property we need at the beginning of the test:

@Test void whenSetProperty_thenLeaksToNextTest() { System.setProperty("app.mode", "debug"); assertThat(System.getProperty("app.mode")) .isEqualTo("debug"); } @Test // <-- flaky test! void whenPropertyNotSet_thenShouldBeNull() { assertThat(System.getProperty("app.mode")) .isNull(); }

However, this approach creates side effects that can affect other tests. In our case, it’ll make whenPropertyNotSet_thenShouldBeNull() test flaky: it can now either pass or fail, depending on the execution order of the two. One way to fix this would be to clear the “app.mode” property before each test, creating a clean environment for each test execution.

2.1. Method-Level Annotations

JUnit 6.1 introduces a built-in extension that helps us manage system properties in a declarative way. For instance, a test that specifically needs a system property to be set can now use the @SetSystemProperty annotation:

@Test @SetSystemProperty(key = "app.mode", value = "debug") void givenSetPropertyAnnotation_whenGetProperty_thenReturnsValue() { assertThat(System.getProperty("app.mode")) .isEqualTo("debug"); }

On the other hand, we can use @ClearSystemProperty to easily remove a system property:

@Test @ClearSystemProperty(key = "app.mode") void whenNoProperty_thenGetPropertyShouldReturnNull() { assertThat(System.getProperty("app.mode")) .isNull(); }

2.2. Repeatable Annotations

Furthermore, the @SetSystemProperty and @ClearSystemProperty annotations can be used together or repeated multiple times. For instance, let’s assume we want to clear the “app.host” and “app.port” properties and set “app.mode” only:

@Test @ClearSystemProperty(key = "app.host") @ClearSystemProperty(key = "app.port") @SetSystemProperty(key = "app.mode", value = "staging") void givenRepeatableAnnotations_whenGetProperties_thenExpectedValues() { assertThat(System.getProperty("app.host")) .isNull(); assertThat(System.getProperty("app.port")) .isNull(); assertThat(System.getProperty("app.mode")) .isEqualTo("staging"); }

2.3. Class-Level Annotations

If we notice we keep using the same setup and cleanup annotations on every test in a class, we can move them to the class level. The extension applies them to each test method in the class, so we avoid repeating ourselves:

@SetSystemProperty(key = "app.mode", value = "staging") @ClearSystemProperty(key = "app.host") class ClassLevelSystemPropertiesUnitTest { // ... }

Moreover, even when the class is annotated, we can still override a system property for a specific test by using a method-level annotation. In our case, let’s say one test needs app.mode to be set to “debug” instead:

@Test @SetSystemProperty(key = "app.mode", value = "debug") void givenMethodLevelAnnotation_whenGetProperty_thenOverridesClassLevel() { assertThat(System.getProperty("app.mode")) .isEqualTo("debug"); }

As expected, the method-level annotation takes precedence for this test only. The other tests in the class still see the class-level value, “staging”.

3. Restoring Properties Set in Code

@SetSystemProperty and @ClearSystemProperty work well when the property values are known upfront, but sometimes a test needs to set properties dynamically: for example, based on parameters or runtime conditions. For those cases, JUnit 6.1 provides @RestoreSystemProperties, which guarantees restoring the properties to their original state once the test finishes.

Let’s imagine testing a function that may set system properties the test is not aware of.

@Test void whenCallingTestedFunction_thenReturnsNotEmptyString() { String result = testedFunction(); assertThat(result).isNotEmpty(); } static String testedFunction() { String randomString = UUID.randomUUID().toString(); System.setProperty(randomString, "dummy-value"); return "done"; }

Cleaning up after such tests can get tedious. Luckily, @RestoreSystemProperties solves this by automatically reverting all system properties to their original state after the test completes:

@Test @RestoreSystemProperties void whenCallingTestedFunction_thenReturnsNotEmptyString() { // ... }

As we can see, applied at the method level, each test gets its own isolated snapshot. Moreover, we can also apply it at the class level, which has the same effect as annotating every test method in the class: each test gets its own snapshot and restores the properties when it finishes.

4. Practical Considerations

Before wrapping up, let’s look at how the extension behaves in parallel test runs and how it compares to other libraries.

4.1. Parallel Execution

By default, JUnit runs tests sequentially. To speed up large test suites, we can enable parallel execution. However, system properties are global state shared by all threads, so reading and writing them in concurrent tests can lead to unpredictable results and flaky tests.

The extension accounts for this. Tests annotated with @SetSystemProperty, @ClearSystemProperty, or @RestoreSystemProperties never run in parallel with each other, because JUnit guards them with resource locks.

However, this doesn’t cover tests whose code reads or writes system properties without these annotations, since they can still run in parallel with the annotated ones. To address this, we can annotate them with @ReadsSystemProperty or @WritesSystemProperty, so that JUnit applies the same locks to them.

4.2. Alternatives

Managing system properties in tests isn’t new, so we may already use a library for it. Let’s see how the built-in extension compares.

JUnit Pioneer offers annotations with the same names, @SetSystemProperty and @ClearSystemProperty. Moving to the built-in extension is therefore mostly a matter of changing the imports and dropping the dependency, as long as we only need system properties. Pioneer remains the better choice if we’re stuck on an older JUnit version.

On the other hand, System Stubs takes a different approach. Instead of annotations only, it provides stub objects that can be injected into tests and changed dynamically at runtime. It also covers more than system properties, including environment variables, System.out, and System.exit calls. If we rely on those features, we should keep it.

Overall, the built-in extension has no extra dependency and is part of JUnit itself. It also integrates with JUnit’s own parallel execution locking, as we saw in the previous section. So, if system properties are all we need, it’s the simplest option.

5. Conclusion

In this tutorial, we discussed JUnit 6.1’s built-in system properties extension. We learned that the API offers annotations such as @SetSystemProperty and @ClearSystemProperty to manage specific system properties, and saw that we can combine or repeat them at a method or class level.

After that, we explored the case where the invoked test code sets system properties that we are not aware of. Therefore, we cannot simply clear them using  @ClearSystemProperty and the property key. For this scenario, we used @RestoreSystemProperties to completely reset the environment to the state prior to the test execution.

Finally, we looked at how the extension behaves during parallel execution, and how it compares to other libraries such as JUnit Pioneer and System Stubs.

As always, the full source code is available over on GitHub.

The post A Guide to the System Properties Extension Annotations in JUnit 6.1 first appeared on Baeldung.