Use Mockito-core for create mock of final class?

て烟熏妆下的殇ゞ 提交于 2019-12-12 16:14:50

问题


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


回答1:


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).



来源:https://stackoverflow.com/questions/29315029/use-mockito-core-for-create-mock-of-final-class

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