3

I find in github example how with standart Mockito make instance of final class (BluetoothGatt.class) :

...
@RunWith(RobolectricTestRunner.class)
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class OnBoardingServiceTest {

    private BluetoothGattCharacteristic characteristic;
    private OnBoardingService service;
    private BluetoothGattReceiver receiver = new BluetoothGattReceiver();

    @Before public void initialise() {
        BleDevice bleDevice = mock(BleDevice.class);
        when(bleDevice.getType()).thenReturn(BleDeviceType.WunderbarMIC);
        BluetoothGatt gatt = mock(BluetoothGatt.class);
...

But From the Mockito FAQ :

What are the limitations of Mockito

  • Needs java 1.5+
  • Cannot mock final classes
  • ...

I checked it is BluetoothGatt from standard android-sdk, so it look like mock final class. Now i try build project , for sure this test working. How it can make mock final class here with core mockito? And if it code finally not working, have you any idea how make mock of final class for android instrumentation testing? (i'm already try PowerMock). Thanks

Community
  • 1
  • 1
Ivied
  • 120
  • 1
  • 8
  • I'm having trouble understanding exactly what you're asking; but I can assure you that core Mockito can NOT mock final classes, whereas PowerMock CAN mock final classes in conjunction with Mockito. – Dawood ibn Kareem Mar 28 '15 at 08:17
  • The Android JVM is not Java's; maybe the rules differ there. The Mockito FAQ does not cover Android's JVM. – fge Mar 28 '15 at 08:23
  • Well, Mockito works by creating a subclass, which is used for the mock. If a class is able to be subclassed, it means that the JVM is not respecting the `final` declaration. It would really surprise me if the Android JVM had this failing. My only thought is that maybe the `RoboelectricTestRunner`, which is used in this example, does some reflection magic to remove the `final`, which is what PowerMock does. – Dawood ibn Kareem Mar 28 '15 at 08:25
  • possible duplicate of [How make mock of final class?](http://stackoverflow.com/questions/29311445/how-make-mock-of-final-class) – Jared Burrows Mar 31 '15 at 01:00

1 Answers1

2

Robolectric is designed to create and substitute implementations of Android standard classes, including final classes and methods. Under the hood, it works in very similar ways to PowerMockito, using its own classloader to establish a classpath that favors its own mocks.

Mock implementations of Android classes in Robolectric are called shadows, and the library is incomplete; you'll probably want to create a custom shadow that suits your needs.

It still may not be easy to use Mockito for method calls, but you can use Robolectric methods to get instances of your shadows, and write shadow implementations that save method arguments into instances (and so forth).

Devstr
  • 4,431
  • 1
  • 18
  • 30
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251