Android unit testing with Junit: testing network/bluetooth resources

随声附和 提交于 2019-12-10 00:56:39

问题


I am slowly becoming obsessed with unit testing. I am trying to develop as much software as I can using test-driven development. I am using JUnit to unit test my android applications.

I have been working on an app that uses bluetooth and am having a hard time unit testing it. I have an Activity that uses BluetoothAdapter to obtain a list of paired and discovered devices. Although it works, I would like to know how to unit test it.

To get the list of paired devices, I call getBondedDevices() on the instance of BluetoothAdapter. The problem is I don't know how to stub or mock this method (or any other bluetoothAdapter method that my Activity calls) so I can't test my Activity against different lists of paired devices.

I thought about using Mockito or trying to subclass BluetoothAdapter to somehow stub out the methods I'm interested in, but it's a final class so I can't do either.

Any ideas on how I could test programs that use BluetoothAdapter or other resources that are (as far as I know) difficult or impossible to stub or mock? As another example, how would you test a program that uses sockets?

thanks in advance for any help

aleph_null


回答1:


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.



来源:https://stackoverflow.com/questions/12102720/android-unit-testing-with-junit-testing-network-bluetooth-resources

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