Junit 5 Pioneer @SetSystemProperty

JUnit Jupiter pioneer @SetSystemProperty is used to temporarily set 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 setSystemProperty(String key) {
        String property = System.getProperty(key);
        return property;
    }
}
package com.example.junit5.sujan;

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

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

class AppleCalculatorTest {
    @Test
    @SetSystemProperty(key = "java.specification.version", value = "1")
    void setSystemPropertyTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals("1", appleCalculator.setSystemProperty("java.specification.version"));
    }
}
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 @SetSystemProperty is a repeatable annotation so if we need to set system property for multiple test cases then instead of writing @SetSystemProperty on each test case, we can annotate class as well, it will temporarily set 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 setSystemProperty(String key) {
        String property = System.getProperty(key);
        return property;
    }
}
package com.example.junit5.sujan;

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

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

@SetSystemProperty(key = "java.specification.version", value = "1")
class AppleCalculatorTest {
    @Test
    void setSystemPropertyTest() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals("1", appleCalculator.setSystemProperty("java.specification.version"));
    }
}
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