JMockit - initialization problem

Filip picture Filip · May 25, 2010 · Viewed 47.9k times · Source

When I use the following test I get a WARNING:

WARNING: JMockit was initialized on demand, which may cause certain tests to fail; please check the documentation for better ways to get it initialized.

This is my test implemenation:

package test;

import static mockit.Mockit.*;
import junit.framework.TestCase;
import mockit.*;
import mockit.integration.junit4.*;


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

import filip.ClassUnderTest;
import filip.LowerClass;

@RunWith(JMockit.class)
public class MockTest extends TestCase {

    @MockClass(realClass = LowerClass.class)
    public static class LowerClassMock {
        @Mock(invocations = 1)
        public String doWork() {
            return "Mockowanie dziala :D";
        }
    }

    @Before
    public void setUp() { setUpMocks(LowerClassMock.class); }

    @After
    public void tearDown() { tearDownMocks(); }

    @Test
    public void testJMockit() {
        ClassUnderTest classUnderTest = new ClassUnderTest();

        classUnderTest.print();
    }

}

Any ideas?

Answer

Gary Rowe picture Gary Rowe · Dec 6, 2010

The accepted answer has fallen a little out of date regarding the links so it's worth mentioning the various solutions directly.

To fix this problem do one of the following:

1 - Specifiy a javaagent

Add this to your JUnit execution environment (for your version):

 -javaagent:path/to/your/jmockit/jmockit-0.998.jar 

2 - configure the Surefire plugin in Maven to avoid it

Add the following to your Maven configuration (choose your own versions)

<!-- JMockit must be before JUnit in the classpath -->
<dependency>
  <groupId>mockit</groupId>
  <artifactId>jmockit</artifactId>
</dependency>
<!-- Standard unit testing -->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
</dependency>

Ensure that your Surefire plugin is configured as follows (for your particular versions):

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.4.3</version>
   <configuration>
      <argLine>-javaagent:${settings.localRepository}/mockit/jmockit/0.998/jmockit-0.998.jar</argLine>
      <useSystemClassLoader>true</useSystemClassLoader>
    </configuration>
 </plugin>

3 - Use the JUnit @RunWith annotation

Add this JUnit runner annotation on each and every test class

@RunWith(JMockit.class)
public class ExampleTest {}