I have a 3rd party singleton instance that my class under test relies on and that singleton is using System.getenv(String)
in its constructor. Is it possible to mock this call?
I tried this
new Expectations()
{
System mockedSystem;
{
System.getenv( "FISSK_CONFIG_HOME" ); returns( "." );
}
};
But it gives me an EXCEPTION_ACCESS_VIOLATION
and crashes the JVM.
Is there another way to set a system environment variable for a unit test?
getenv(String name) method gets the value of the specified environment variable. An environment variable is a system-dependent external named value. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH).
getenv. public static Map<String,String> getenv() Returns an unmodifiable string map view of the current system environment. The environment is a system-dependent mapping from names to values which is passed from parent to child processes.
In this case you need to use partial mocking so that JMockit doesn't redefine everything in the System class. The following test will pass:
@Test
public void mockSystemGetenvMethod()
{
new Expectations()
{
@Mocked("getenv") System mockedSystem;
{
System.getenv("envVar"); returns(".");
}
};
assertEquals(".", System.getenv("envVar"));
}
I will soon implement an enhancement so that issues like this don't occur when mocking JRE classes. It should be available in release 0.992 or 0.993.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With