Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System clear Property doesn't work. How can it be?

Tags:

java

I really don't understand!

I run unit tests which contains cod:

  String progDir = "prog.dir";
  System.clearProperty(progDir);
  System.out.println(System.getProperty(progDir));

And on console I see prog dir path. Although there must be null.

I setting this variable in setUp block. This is junit test. This variable need for all other test but not for that, so I tried to clean it in the start of this test method. If I remove setting of this var from setUp block this test will pass.

System.setProperty work fine.

How can it be? Thanx

like image 642
Maxim Ostrovsky Avatar asked Apr 25 '13 15:04

Maxim Ostrovsky


People also ask

How to clear system properties in Java?

The java. lang. System. clearProperty() method removes the system property indicated by the specified key.

How does system setProperty work?

The setProperty method has two attributes – “propertyName” and “value.” The propertyName represents the name of the browser-specific driver, and the value points to the path of that browser driver.

Is system getProperty thread safe?

getProperty is okay but System. setProperty is never good. Wherever you store state, third-party libraries will be able to read it using reflection if they want. If you don't trust third-party libraries, don't use them.

How do I set system properties in Junit?

If your test relies on system properties you could set them and unset them in 'before' and 'after' lifecycle methods. In Junit5, setting system properties for all tests in a test case might look like this: @BeforeAll public static void setSystemProperties() { // set the system properties // ... }


1 Answers

If a property is not defined in a Properties object, then getProperty will look up in the parent Properties object

Properties javadoc says:

public String getProperty(String key)

Searches for the property with the specified key in this property list. If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked. The method returns null if the property is not found.

clearProperty calls Hashtable.remove since remove is not overridden in Properties so does not affect the default property list.

So it is quite possible for a cleared property to still be visible via getProperty since the System javadoc does not specify whether system Properties are layered or flat.

like image 194
Mike Samuel Avatar answered Sep 19 '22 14:09

Mike Samuel