Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to JMockIt System.getenv(String)?

What I have right now

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

JMockIt Example

    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?

like image 731
cringe Avatar asked Oct 27 '09 10:10

cringe


People also ask

How do I get system Getenv?

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).

What is system getenv()?

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.


1 Answers

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.

like image 83
Rogério Avatar answered Oct 01 '22 10:10

Rogério