Android单元测试:模拟BluetoothDevice并写入parcel

时间:2017-05-03 21:29:20

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

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

我的对象是一个简单的对象,它包含一些原始变量和一个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);
    }
}

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

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

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

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

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

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

是否有任何单位使用模拟BluetoothDevice进行测试并且可以给我一些提示?谢谢

2 个答案:

答案 0 :(得分:2)

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

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

干杯

答案 1 :(得分:0)

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

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

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

  • 使用BluetoothAdapter#getRemoteDevice(字符串地址)创建设备对象。

使用last方法获取BluetoothDevice对象时(或使用new方法创建新对象) BluetoothDevice(地址)),连接尝试只有在以下情况下才能起作用:

  • 设备具有PUBLIC地址或已绑定,或
  • 在尝试连接之前,设备至少扫描过一次 自蓝牙适配器启动以来

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