Junit 5 Pioneer @ClearEnvironmentVariable

JUnit Jupiter pioneer @ClearEnvironmentVariable is used to temporarily clear the environment variables for test execution. Once the test execution completes, its default value will be restored.

package com.example.junit5.sujan;

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

import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.ClearEnvironmentVariable;
import org.junitpioneer.jupiter.SetEnvironmentVariable;

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

class AppleCalculatorTest {
    @Test
    @ClearEnvironmentVariable(key = "USERNAME")
    void setEnvironmentVariableTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertNull( appleCalculator.getEnvironmentVariable("USERNAME"));
    }
}

 

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'
}

JUnit Jupiter @ClearEnvironmentVariable is a repeatable annotation so if we need to clear system envirnment variable for multiple test cases then instead of writing @ClearEnvironmentVariable 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 getEnvironmentVariable(String key) {
            String property = System.getenv(key);
            return property;
        }
    }
package com.example.junit5.sujan;

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

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

class AppleCalculatorTest {
    @Test
    @ClearEnvironmentVariable(key = "USERNAME")
    void setEnvironmentVariableTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertNull(appleCalculator.getEnvironmentVariable("USERNAME"));
    }
}
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