JMockit javaagent isn't initializing JMockit

回眸只為那壹抹淺笑 提交于 2019-12-22 10:48:29

问题


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)



来源:https://stackoverflow.com/questions/20672198/jmockit-javaagent-isnt-initializing-jmockit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!