【问题标题】:Android unit test: mock BluetoothDevice and write to parcelAndroid单元测试:模拟BluetoothDevice并写入包裹
【发布时间】:2017-05-03 21:29:19
【问题描述】:

我想询问有关单元测试具有BluetoothDevice 变量的类的问题。

我的对象是一个简单的对象,它包含一些原始变量和一个 BluetoothDevice 变量。我的对象也是可包裹的。

最终我的代码在移动设备上运行良好,但运行单元测试时出现奇怪的错误。

我在测试类中模拟了蓝牙设备如下图:

@RunWith(RobolectricTestRunner.class)
@Config(manifest=Config.NONE)
public class BluetoothDeviceTest {

    @Mock
    BluetoothDevice device1;

    @Before
    public void initMocks(){
        MockitoAnnotations.initMocks(this);

        when(device1.getAddress()).thenReturn("01:02:03:04:05:06");
        when(device1.getName()).thenReturn("device767b1");
        when(device1.getBondState()).thenReturn(BOND_NONE);
    }
}

在我使用的其他原语中的对象中:

  • 我在@Override public void writeToParcel(Parcel out, int flags) 方法中使用out.writeParcelable(mBluetoothDevice,0);

  • 我在protected MyObject(Parcel in) 构造函数中使用mBluetoothDevice = in.readParcelable(BluetoothDevice.class.getClassLoader());

测试我的对象实例打包的单元测试失败并出现异常 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

再次请注意,当我的代码运行完全正常并且打包在我正在开发的移动应用程序中运行良好时。只有单元测试表现得很奇怪。

我怀疑这是因为我的模拟 BluetoothDevice 变量在包裹中比正常的真实实例短,并且包裹中数据字段的顺序被弄乱了。

有没有人用模拟的BluetoothDevice 进行单元测试并且可以给我一些提示?谢谢

【问题讨论】:

  • 为了避免使用 Robolectric(即你只想要 JUnit),你必须正确地模拟 Parcel,没有伪装会起作用。我确实有一个如何工作的简单实现,但它仅限于 Parcelable 问题(与蓝牙无关)。这是:gist.github.com/milosmns/7f6448a3602595948449d3bfaff9b005

标签: java android unit-testing mocking android-bluetooth


【解决方案1】:

迟到的答案......但如果有人需要的话。 Robolectric 现在有一个类 ShadowBluetoothDevice

可以这样使用:ShadowBluetoothDevice.newInstance("00:11:22:33:AA:BB")

干杯

【讨论】:

    【解决方案2】:

    为了连接到 BLE 设备,应用需要获取 BluetoothDevice 对象。这可以使用以下方法之一来完成 三种方法:

    • 通过扫描:在回调中为每个扫描的广告数据包返回一个 BluetoothDevice 对象 参数 ScanResult。

    • 通过使用 BluetoothAdapter#getBondedDevices() 获取绑定设备列表。

    • 通过使用 BluetoothAdapter#getRemoteDevice(String address) 创建设备对象。

    当使用 last 方法获得一个 BluetoothDevice 对象时(或通过使用 new 创建一个新对象) BluetoothDevice(address)),只有在以下情况下才会尝试连接它:

    • 设备具有公共地址或已绑定,或
    • 在尝试连接之前至少已扫描设备一次 因为蓝牙适配器已经启动

    来源:https://devzone.nordicsemi.com/blogs/1046/what-to-keep-in-mind-when-developing-your-ble-andr/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多