eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

eBook – Guide Junit – NPI (tag = JUnit)
announcement - icon

Improve your tests with JUnit 5, from mastering the basics to employing the new powerful features from JUnit 5 like extensions, tagging, filtering, parameterized tests, and more:

>> The Junit 5 handbook

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.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest