beatngu13
beatngu13

Reputation: 9353

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?

Upvotes: 28

Views: 36454

Answers (3)

beatngu13
beatngu13

Reputation: 9353

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);
    // ...
}

Upvotes: 32

Ashley Frieze
Ashley Frieze

Reputation: 5443

The JUnit Pioneer way requires the system properties to be known at compile time. Where they are generated at runtime, say via Testcontainers or Wiremock creating things on random ports, it may be better to use something which can be driven from dynamic values.

The problem can be solved with System Stubs https://github.com/webcompere/system-stubs which provides JUnit 5 and is a fork of the code from System Lambda, itself built by the author of System Rules.

@ExtendWith(SystemStubsExtension.class)
class SomeTest {
    // can be initialised here with some up front properties
    // or leave like this for auto initialization
    @SystemStub
    private SystemProperties someProperties;

    @BeforeEach
    void beforeEach() {
        someProperties.set("prop1", "value1")
            .set("prop2", "value2");
    }

    @Test
    void someTest() {
        // properties are set here
        // and can also call System.setProperty


        // properties reset to state before the test case ran
        // as the test case is tidied up
    }
}

Upvotes: 4

schrieveslaach
schrieveslaach

Reputation: 1819

You can use the extension API. You could create an annotation which defines your extension to a test method.

import org.junit.jupiter.api.extension.ExtendWith;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@ExtendWith(SystemPropertyExtension.class)
public @interface SystemProperty {

    String key();

    String value();
}

Then, you can create the extension class:

import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class SystemPropertyExtension implements AfterEachCallback, BeforeEachCallback {

    @Override
    public void afterEach(ExtensionContext extensionContext) throws Exception {
        SystemProperty annotation = extensionContext.getTestMethod().get().getAnnotation(SystemProperty.class);
        System.clearProperty(annotation.key());
    }

    @Override
    public void beforeEach(ExtensionContext extensionContext) throws Exception {
        SystemProperty annotation = extensionContext.getTestMethod().get().getAnnotation(SystemProperty.class);
        System.setProperty(annotation.key(), annotation.value());
    }
}

Finally, you can annotate your test with properties:

@Test
@SystemProperty(key = "key", value = "value")
void testPropertey() {
    System.out.println(System.getProperty("key"));
}

This solution supports only one system property for each test. If you want to support multiple test, you could use a nested annotation and the extension could handle this as well:

@Test
@SystemProperties({
    @SystemProperty(key = "key1", value = "value"),
    @SystemProperty(key = "key2", value = "value")
})
void testPropertey() {
    System.out.println(System.getProperty("key1"));
    System.out.println(System.getProperty("key2"));
}

Upvotes: 14

Related Questions