How to JMockIt System.getenv(String)?

java, jmockit, unit-testing

Solution

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.

Problem

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?

Original source