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

解决方案

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.

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐