How is JMockIt System.getenv (String)?

What I have right now

I have a third-party singleton instance in which my class runs under testing, and this singleton uses System.getenv(String)in its constructor. Is it possible to mock this challenge?

I tried this

JMockIt example

    new Expectations()
    {

        System mockedSystem;
        {
            System.getenv( "FISSK_CONFIG_HOME" ); returns( "." );
        }
    };

But he gives me EXCEPTION_ACCESS_VIOLATIONand gives the JVM.

Is there any other way to set the system environment variable for unit test?

+5
source share
5 answers

In this case, you need to use partial bullying so that JMockit does not override 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"));
   }

, , JRE. 0.992 0.993.

+15

PowerMock , .

( API) Facade API , , .

, JMockIt :    ;

import static org.junit.Assert.*;

import mockit.*;
import mockit.integration.junit4.JMockit;

import org.junit.*;
import org.junit.runner.RunWith;

@RunWith(JMockit.class)
public class JMockItTest {

 @Test
 public void mockSystemGetEnv() {
  Mockit.setUpMocks(MockSystem.class); 

  assertEquals("Bye", System.getenv("Hello"));

 }

 @MockClass(realClass = System.class)
 public static class MockSystem {
  @Mock
  public static String getenv(String str) {
   return "Bye";
  }
 }

}
+3

, : System.getenv() , .

[EDIT] , . Java . , . . IDE .

, , .

+2

Update by @ Rogério.

In my case with JMockit 1.25, I had to do this using the MockUp API:

@Test
public void mockSystemGetenvMethod(){
    new MockUp<System>()
    {
        @Mock
        public String getenv(final String string) {
            return "";
        }
    };

    assertEquals(".", System.getenv("envVar"));
}
0
source

All Articles