6

I'm trying to implement a unit test using Robolectric to replace the stubbed methods in android.jar while also using jMockit to mock an Android class (Fragment, in my case). However, I can't seem to get it to work. If I annotate the test class with @RunWith(RobolectricTestRunner.class), I get:

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)

If I use @RunWith(JMockit.class) or no @RunWith, I get "Stub!" exceptions.

At the moment, my classpath has things in the following order: robolectric, jmockit, junit, android.

Anybody out there been able to get jmockit and robolectric to play well together?

leppie
  • 115,091
  • 17
  • 196
  • 297
Andy Dennie
  • 6,012
  • 2
  • 32
  • 51

2 Answers2

5

This should be possible. I haven't tested this, but you can create your own test runner.

Take a look at the source for the JMockit and Robolectric test runners:

Of the two the Robolectric one is much more complicated, so we don't want to duplicate that functionality. The JMockit test runner is fairly simple. It should work to extend the RobolectricTestRunner and include the JMockit functionality.

import mockit.internal.startup.*;
class MyTestRunner extends RobolectricTestRunner {

   static { Startup.initializeIfNeeded(); }

   /**
    * Constructs a new instance of the test runner.
    *
    * @throws InitializationError if the test class is malformed
    */
   public MyTestRunner(Class<?> testClass) throws InitializationError
   {
      super(testClass);
   }
}
Joe
  • 3,059
  • 2
  • 22
  • 28
  • @Joe, I was looking to try similar approach for PowerMock and Robolectric. But I failed in quick tour. It's quite complicated. Maybe I will do second round :) – Eugen Martynov Feb 22 '13 at 12:48
  • This did not help. The problem is, as soon as I add JMockit dependency to the project (without actually using it anywhere), the Roboelectric tests start to fail with "No compatible method found: fireTestRunStarted" – altumano Mar 16 '13 at 18:26
2

At version Version 1.8 (Apr 27, 2014) JMockit can work in conjunction with Robolectric.

JMockit now works fine with the Robolectric Android testing tool (tested with Robolectric 2.2 and 2.3).

http://jmockit.org/changes.html

Nhat Dinh
  • 3,378
  • 4
  • 35
  • 51