![JAR search and dependency download from the Maven repository](/logo.png)
org.junit.contrib.java.lang.system.ClearSystemProperties Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of system-rules Show documentation
Show all versions of system-rules Show documentation
A collection of JUnit rules for testing code which uses java.lang.System.
package org.junit.contrib.java.lang.system;
import static java.lang.System.clearProperty;
import org.junit.rules.ExternalResource;
/**
* The {@code ClearSystemProperty} rule clears a set of system properties to a
* test. After the test the original values are restored.
*
* Let's assume the system property {@code MyProperty} has the value
* {@code MyValue}. Now run the test
*
*
* public void MyTest {
* @Rule
* public final ClearSystemProperty myPropertyIsCleared
* = new ClearSystemProperty("MyProperty");
*
* @Test
* public void overrideProperty() {
* assertNull(System.getProperty("MyProperty"));
* }
* }
*
*
* The test succeeds and after the test, the system property {@code MyProperty}
* has the value {@code MyValue}.
*
* The {@code ClearSystemProperty} rule accepts a list of properties:
*
*
* @Rule
* public final ClearSystemProperty myPropertyIsCleared = new ClearSystemProperty(
* "first", "second", "third");
*
*/
public class ClearSystemProperties extends ExternalResource {
private final RestoreSystemProperties restoreSystemProperty;
private final String[] names;
public ClearSystemProperties(String... names) {
this.names = names;
this.restoreSystemProperty = new RestoreSystemProperties(names);
}
@Override
protected void before() throws Throwable {
backupOriginalValue();
clearProperties();
}
@Override
protected void after() {
restoreOriginalValue();
}
private void backupOriginalValue() throws Throwable {
restoreSystemProperty.before();
}
private void clearProperties() {
for (String name : names)
clearProperty(name);
}
private void restoreOriginalValue() {
restoreSystemProperty.after();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy