Skip to content Skip to sidebar Skip to footer

How Make Mock Of Final Class?

Work in AndroidStudio. Want make mock of final class for AndroidInstrumentalTest with PowerMock. Added libs in gradle: androidTestCompile ('org.powermock:powermock-api-mockito:1.5

Solution 1:

On non-rooted devices, APKs are subject to "verification", where the VM ensures that classes refer only to the implementations they are compiled against. Emulators and rooted devices aren't subject to this rule.

Unfortunately, implementations that hack classloaders (PowerMock and Robolectric) almost always violate that rule, because they create unexpected static class and method implementations (in order to mock them).

Keep the classloader hacking to your JVM unit tests, not your instrumentation tests, and instead extract any relevant interfaces into a wrapper you can control (and mock).


Solution 2:

Have you tried using Robolectric + Mockito?.

I believe you have the right idea. It should be as simple as:

BluetoothGatt gatt = mock(BluetoothGatt.class);

Please take a look at this example:

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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);
    BluetoothGattService gattService = mock(BluetoothGattService.class);
    when(gatt.getServices()).thenReturn(Arrays.asList(gattService));
    when(gattService.getUuid()).thenReturn(fromString("00002001-0000-1000-8000-00805f9b34fb"));
    characteristic = mock(BluetoothGattCharacteristic.class);
    when(gattService.getCharacteristics()).thenReturn(Arrays.asList(characteristic));

    service = new OnBoardingService(bleDevice, gatt, receiver);
}

Source: https://github.com/relayr/android-sdk/blob/master/tests/src/androidTest/java/io/relayr/ble/service/OnBoardingServiceTest.java https://github.com/relayr/android-sdk/blob/master/tests/src/androidTest/java/io/relayr/ble/service/BluetoothGattReceiverTest.java


Post a Comment for "How Make Mock Of Final Class?"