Junit 5 Pioneer @ClearSystemProperty

JUnit Jupiter pioneer @ClearSystemProperty is used to temporarily clear the system property for test execution. Once the test execution completes, its default value will be restored.

package com.example.junit5.sujan;

public class AppleCalculator {
    public String clearSystemProperty(String key) {
        String property = System.getProperty(key);
        return property;
    }
}
package com.example.junit5.sujan;

import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.ClearSystemProperty;

import static org.junit.jupiter.api.Assertions.assertNull;

class AppleCalculatorTest {
    @Test
    @ClearSystemProperty(key = "java.runtime.name")
    void clearSystemPropertyTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertNull(appleCalculator.clearSystemProperty("java.runtime.name"));
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.junit-pioneer:junit-pioneer:0.6.0'
}
test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}

 

JUnit Jupiter @ClearSystemProperty is a repeatable annotation so if we need to clear system property for multiple test cases then instead of writing @ClearSystemProperty on each test case, we can annotate class as well, it will temporarily clear the specific system property for all the test cases of that class. Once the test execution completes, its default value will be restored.

package com.example.junit5.sujan;

public class AppleCalculator {
    public String clearSystemProperty(String key) {
        String property = System.getProperty(key);
        return property;
    }
}
package com.example.junit5.sujan;

import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.ClearSystemProperty;

import static org.junit.jupiter.api.Assertions.assertNull;

@ClearSystemProperty(key = "java.runtime.name")
class AppleCalculatorTest {
    @Test
    void clearSystemPropertyTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertNull(appleCalculator.clearSystemProperty("java.runtime.name"));
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.junit-pioneer:junit-pioneer:0.6.0'
}

follow us on