org.junit.rules.TestRulepublic class ClearSystemProperties
extends org.junit.rules.ExternalResource
ClearSystemProperties rule clears a set of system
properties when the test starts and restores their original values
when the test finishes (whether it passes or fails).
Supposing that the system property YourProperty has the
value YourValue. Now run the test
public void YourTest {
@Rule
public final TestRule clearSystemProperties
= new ClearSystemProperties("YourProperty");
@Test
public void verifyProperty() {
assertNull(System.getProperty("YourProperty"));
}
}
The test succeeds and afterwards the system property
YourProperty has the value YourValue again.
The ClearSystemProperties rule accepts a list of
properties in case you need to clear multiple properties:
@Rule
public final TestRule clearSystemProperties
= new ClearSystemProperties("first", "second", "third");
If you want to clear a property for a single test then you can
use
RestoreSystemProperties
along with System.clearProperty(String).
@Rule
public final TestRule restoreSystemProperties
= new RestoreSystemProperties();
@Test
public void test() {
System.clearProperty("YourProperty");
...
}| Constructor | Description |
|---|---|
ClearSystemProperties(java.lang.String... properties) |
Creates a
ClearSystemProperties rule that clears the specified
properties and restores their original values when the test finishes
(whether it passes or fails). |
| Modifier and Type | Method | Description |
|---|---|---|
protected void |
after() |
|
protected void |
before() |
|
void |
clearProperty(java.lang.String property) |
Deprecated.
Please use
RestoreSystemProperties
along with System.clearProperty(String). |
public ClearSystemProperties(java.lang.String... properties)
ClearSystemProperties rule that clears the specified
properties and restores their original values when the test finishes
(whether it passes or fails).properties - the properties' names.@Deprecated public void clearProperty(java.lang.String property)
RestoreSystemProperties
along with System.clearProperty(String).This method is deprecated. If you're still using it, please replace your current code
@Rule
public final ClearSystemProperties clearSystemProperties = new ClearSystemProperties();
@Test
public void test() {
clearSystemProperties.clearProperty("YourProperty");
...
}
with this code:
@Rule
public final TestRule restoreSystemProperties = new RestoreSystemProperties();
@Test
public void test() {
System.clearProperty("YourProperty");
...
}property - the name of the property.protected void before()
throws java.lang.Throwable
before in class org.junit.rules.ExternalResourcejava.lang.Throwableprotected void after()
after in class org.junit.rules.ExternalResourceCopyright © 2011–2018. All rights reserved.