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

Ben*_*ust 0 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我用的是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变量在包裹中比正常的真实实例短,并且包裹中数据字段的顺序变得混乱。

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

Nic*_*as 5

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

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

干杯