我慢慢地沉迷于单元测试。我正在尝试使用测试驱动开发来开发尽可能多的软件。我正在使用 JUnit 对我的 Android 应用程序进行单元测试。
我一直在开发一个使用蓝牙的应用程序,并且很难对其进行单元测试。我有一个活动,它使用蓝牙适配器来获取已配对和发现的设备的列表。虽然它有效,但我想知道如何对其进行单元测试。
为了获取配对设备的列表,我在 BluetoothAdapter 的实例上调用 getBondedDevices()。问题是我不知道如何存根或模拟此方法(或我的活动调用的任何其他 bluetoothAdapter 方法),因此我无法针对不同的配对设备列表测试我的活动。
我考虑过使用 Mockito 或尝试子类化 BluetoothAdapter 以某种方式消除我感兴趣的方法,但它是最终类,所以我也不能这样做。
关于如何测试使用蓝牙适配器或其他资源(据我所知)很难或不可能存根或模拟的程序,有什么想法吗?另一个例子,如何测试使用套接字的程序?
预先感谢您的帮助
aleph_null
为了测试您的活动,您可以重构您的代码。介绍一个BluetoothDeviceProvider
使用默认实现。
public interface BluetoothDeviceProvider {
Set<BluetoothDevice> getBluetoothDevices();
}
public class DefaultBluetoothDeviceProvider implements BluetoothDeviceProvider {
public Set<BluetoothDevice> getBluetoothDevices() {
return new BluetoothAdapter.getDefaultAdapter().getBondedDevices();
}
}
然后在活动中注入这个新接口:
public class MyActivity extends Activity {
private BluetoothDeviceProvider bluetoothDeviceProvider;
public MyActivity(BluetoothDeviceProvider bluetoothDeviceProvider) {
this.bluetoothDeviceProvider = bluetoothDeviceProvider;
}
protected void onStart() {
Set<BluetoothDevice> devices = bluetoothDeviceProvider.getBluetoothDevices();
...
}
...
}
现在该活动似乎可以进行单元测试。但蓝牙设备仍然是最终版本,您无法在活动中注入模拟。所以你必须重构这个新代码并引入一个新的接口来包装BluetoothDevice...->核心android类上的抽象层。
最后,可以通过各种单元测试来检查活动行为...因此新引入的接口的实现仍有待测试。为此,您可以:
另请查看此 wiki 页面使用 PowerMock 模拟最终类 https://code.google.com/p/powermock/wiki/MockFinal.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)