【问题标题】:Android unit testing with Junit: testing network/bluetooth resources使用 Junit 进行 Android 单元测试:测试网络/蓝牙资源
【发布时间】:2012-08-19 14:58:00
【问题描述】:

我逐渐沉迷于单元测试。我正在尝试使用测试驱动开发尽可能多地开发软件。我正在使用 JUnit 对我的 android 应用程序进行单元测试。

我一直在开发一个使用蓝牙的应用程序,并且很难对其进行单元测试。我有一个 Activity 使用 BluetoothAdapter 来获取配对和发现的设备列表。虽然它有效,但我想知道如何对其进行单元测试。

为了获取配对设备列表,我在 BluetoothAdapter 实例上调用 getBondedDevices()。问题是我不知道如何存根或模拟此方法(或我的 Activity 调用的任何其他 bluetoothAdapter 方法),因此我无法针对不同的配对设备列表测试我的 Activity。

我考虑过使用 Mockito 或尝试将 BluetoothAdapter 子类化以以某种方式删除我感兴趣的方法,但它是最后一个类,所以我也不能这样做。

关于如何测试使用 BluetoothAdapter 或其他(据我所知)难以或不可能存根或模拟的资源的程序有什么想法吗?再举一个例子,你将如何测试一个使用套接字的程序?

提前感谢您的帮助

aleph_null

【问题讨论】:

  • sscce 会有所帮助。
  • 您是否找到了解决方案或解决方案的提示,或者您是否最终重构了现有代码以允许类似于以下建议的内容?
  • @Rastikan 我记不太清了,但我可能使用了最新版本的 Robolectric 来完成这项工作。现在,我没有尽可能多地进行测试,因为 Android 上的单元测试支持真的很糟糕。
  • 这希望在去年有所改变@aleph_null .. 有什么提示吗?

标签: android unit-testing junit mocking stub


【解决方案1】:

为了测试您的活动,您可以重构您的代码。引入带有默认实现的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 类的抽象层。

最后,活动行为可以通过各种单元测试来检查......所以新引入的接口的实现仍有待测试。为此,您可以:

  • 不要让它们(单元)测试,对我来说不是什么大问题,因为它们只是进行委派

  • 看看PowerMock

还可以查看有关 mocking final classes using PowerMock 的 wiki 页面。

【讨论】:

  • 虽然将类包装在接口/具体类中很乏味,但为了测试重要特性可能值得这样做。感谢您的回答。我肯定会研究 PowerMock,知道它是否与 Android 兼容?
  • 我从未在Android上尝试过PowerMock,但它似乎兼容,看看this post
  • 我知道是几年后的事了,但是 Mockito 2.+ 现在可以模拟最终课程了.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
相关资源
最近更新 更多