Tuesday, 17 May 2016

How JMockit mocks static methods?

Dependency:
* Using old version

    <!-- jmockit should be before Junit -->
    <dependency>
      <groupId>com.googlecode.jmockit</groupId>
      <artifactId>jmockit</artifactId>
      <version>1.7</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

Code:

import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.junit.Before;
import org.junit.Test;

import static mockit.Deencapsulation.invoke;
import static org.junit.Assert.assertEquals;

public class JMockitStaticMethod {

  @Mocked({"getenv"})
  private System system;

  @Before
  public void init()
  {
    // allow to return mock value any number of times
    new NonStrictExpectations(system)
    {
      {
        invoke(System.class, "getenv", "MOCKED_VALUE");
        returns("MOCKED");
      }
    };
  }

  @Test
  public void testJMockitStatic() {
    assertEquals("MOCKED", System.getenv("MOCKED_VALUE"));
  }

}


Dependency:
* Using new version:

  <!-- jmockit should be before Junit -->
    <dependency>
      <groupId>org.jmockit</groupId>
      <artifactId>jmockit</artifactId>
      <version>1.23</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>


Code (mocks easier):

import mockit.Expectations;

import org.junit.Before;
import org.junit.Test;

import static mockit.Deencapsulation.invoke;
import static org.junit.Assert.assertEquals;

public class JMockitStaticMethod {


  @Before
  public void init()
  {
    new Expectations(System.class)
    {
      {
        invoke(System.class, "getenv", "MOCKED_VALUE");
// returns("MOCKED")
        result = new ClassCastException();
      }
    };
  }

  @Test(expected = ClassCastException.class)
  public void testJMockitStatic() {
    assertEquals("MOCKED", System.getenv("MOCKED_VALUE"));
  }

}

No comments:

Post a Comment