JUnit Jupiter pioneer @
SetEnvironmentVariable is used to temporarily set the environment 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 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.SetEnvironmentVariable;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AppleCalculatorTest {
@Test
@SetEnvironmentVariable(key = "USERNAME", value = "apple")
void setEnvironmentVariableTest() {
AppleCalculator appleCalculator = new AppleCalculator();
assertEquals("apple", 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 @
SetEnvironmentVariable is a repeatable annotation so if we need to set environment property for multiple test cases then instead of writing @
SetEnvironmentVariable on each test case, we can annotate class as well, it will temporarily set the specific environment variable 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.SetEnvironmentVariable;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SetEnvironmentVariable(key = "USERNAME", value = "apple")
class AppleCalculatorTest {
@Test
void setEnvironmentVariableTest() {
AppleCalculator appleCalculator = new AppleCalculator();
assertEquals("apple", 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'
}