2017-05-03 71 views
0

我想问一下关于具有BluetoothDevice变量的类的单元测试。安卓单元测试:模拟BluetoothDevice并写入包裹

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

最终,我的代码在移动设备上完全正常工作,但运行我的单元测试时出现奇怪的错误。

我嘲笑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)构造函数。

,测试我的对象实例的瓜分单元测试失败,异常 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

再次请注意,当我的代码运行完全正常,并瓜分工作在移动应用程序,我的工作好

。只有单元测试是奇怪的。

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

有没有人测试过一个嘲讽BluetoothDevice,可以给我一些提示?谢谢

回答

0

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

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

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

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

当使用后一种方法获得的BluetoothDevice类对象(或通过产生具有一个新的对象新 BluetoothDevice类(地址)),尝试连接到它的工作仅当:

  • 的设备具有公共地址或粘结,或
  • 该设备已自蓝牙适配器已启动之前尝试连接 扫描至少一次

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