JMockit javaagent isn't initializing JMockit

2019-05-10 14:54发布

问题:

I've set up JMockit for use with some JUnit tests also using Robolectric, but I am getting errors. I'm primarily using maven to run the tests.

When I run the test with mvn test and the javaagent configured as specified here I get the usual exception:

java.lang.IllegalStateException: JMockit wasn't properly initialized; check that jmockit.jar precedes junit.jar in the classpath (if using JUnit; if not, check the documentation)

I have validated that JMockit is on the classpath before JUnit using mvn dependency:build-classpath and mvn test --debug. I have also validated that the -javaagent argument is appropriately being called using mvn test --debug.

Library versions:

  • JDK 1.6
  • JMockit 1.5
  • JUnit 4.8.2
  • Robolectric 2.2 The Robolectric runner prevents me from using the JMockit runner.
  • Maven 3.0.3
  • Surefire 2.14.1

The test class follows:

@RunWith(RobolectricTestRunner.class)
public class HelpFragTest {

    FragmentActivity activity;
    FragmentManager fragmentManager;
    @Mocked ActionBarManager actionBarManager;

    @Before
    public void setup() throws Exception {
        activity = Robolectric.buildActivity(FragmentActivity.class).create().resume().get();
        fragmentManager = activity.getSupportFragmentManager();
        MyApplication.instance().setActionBarManager(actionBarManager);
    }

    @Test
    public void testShow(){
        new NonStrictExpectations() {{
            Helper.staticMethod(anyString, anyString);
            actionBarManager.clear();
            actionBarManager.setTitle(anyString);
            actionBarManager.refresh();
        }};
        HelpFrag frag = HelpFrag.newInstance();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(frag, StringUtils.EMPTY);
        transaction.commit();

        assertTrue(frag.isVisible());

    }
}

I've also tried without either the explicit runner or the JavaAgent, in which case I get the following exception from the same code:

java.lang.IllegalStateException: Invalid place to record expectations

回答1:

I have run into the same issue, and the problem seems to be that the Robolectric test runner interferes with the JMockit-JUnit integration. See this.



回答2:

SYMPTOM: Error when run maven with Jmockit and junit into java project.

MESSAGE: JMockit wasn't properly initialized; check that jmockit.jar precedes junit.jar in the classpath (if using JUnit; if not, check the documentation)

CAUSES:

Wrong configured in POM.xml file. Jmockit dependencyis is after of junit.

SOLUTIONS:

Edit POM.xml file. The jmockit.jar should be precedes junit.jar then jmockit dependency should be before of junit.

(always put jmockit before of junit)