Android unit testing with Junit: testing network/bluetooth resources

拈花ヽ惹草 提交于 2019-12-04 23:05:24
gontard

To test your activity, you may refactor your code. Introduce a BluetoothDeviceProvider with a default implementation.

public interface BluetoothDeviceProvider {
    Set<BluetoothDevice> getBluetoothDevices();
}

public class DefaultBluetoothDeviceProvider implements BluetoothDeviceProvider {
    public Set<BluetoothDevice> getBluetoothDevices() {
        return new BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    }
}

then inject this new interface, in the activity :

public class MyActivity extends Activity {
    private BluetoothDeviceProvider bluetoothDeviceProvider;

    public MyActivity(BluetoothDeviceProvider bluetoothDeviceProvider) {
        this.bluetoothDeviceProvider = bluetoothDeviceProvider;
    }

    protected void onStart() {
        Set<BluetoothDevice> devices = bluetoothDeviceProvider.getBluetoothDevices();
        ... 
    }
    ...
}

Now the activity seems unit-testable. But the BluetoothDevice is still final and you can't inject a mock in your activity. So you have to refactor this new code and introduce a new interface that wraps the BluetoothDevice... -> an abstraction layer upon the core android classes.

At the end the activity behavior can be checked via various unit tests... So the implementations of the newly introduced interfaces remains to test. To do this, you can :

  • keep them not (unit) tested, not a big problem for me since they just do delegation

  • look at PowerMock.

Also check this wiki page about mocking final classes using PowerMock.

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