【发布时间】: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