我正在开发一个Android应用程序(API 15),在尝试编写单元测试时遇到了以下问题:
我使用android.os.Parcel保存一个类(例如,如果屏幕被翻转),并将其发送到另一个活动。如果我尝试像这样对Parcel方法进行单元测试(这是我从互联网上获得的):
@Test
public void testParcel() {
Comment test = new Comment();
test.setId(testNr0Id);
test.setComment(testNr0String);
// Obtain a Parcel object and write the parcelable object to it:
Parcel parcel = Parcel.obtain();
test.writeToParcel(parcel, 0);
// After you're done with writing, you need to reset the parcel for reading:
parcel.setDataPosition(0);
// Reconstruct object from parcel and asserts:
Comment createdFromParcel = Comment.CREATOR.createFromParcel(parcel);
assertEquals(test, createdFromParcel);
}然后我得到一个NullPointerException,因为从Parcel.obtain()返回的Parcel是空的。JavaDoc只是说这个方法“从池中返回一个包裹对象”。现在我的问题是:哪个池?为什么这个Parcel-Object为空?有什么建议可以让这个测试运行吗?
谢谢你的帮忙
迈克尔
发布于 2015-11-04 00:30:32
我也遇到过同样的问题。但是,在我将测试从test目录移到androidTest目录后,一切都开始正常工作。我认为这是因为Parcel类是系统一类,所以也需要对其进行检测。
发布于 2018-06-01 07:13:05
为了避免去Robolectric或安卓测试(也就是说,你只想留在JUnit,没有设备连接等),你可以使用Mockito模拟包裹内的所有东西。我有一个简单的实现,我在我的所有项目中使用它(是的,它真的很有效,它在内存中存储数据):
https://gist.github.com/milosmns/7f6448a3602595948449d3bfaff9b005
基本的想法是有一个后备存储(即一个列表),并将其中的所有内容都推入其中-但您确实需要在内部使用Mockito模拟一个Parcel才能使其工作。我注释掉了一些数据类型,但您会明白的。:)
这是阅读和各种方法的结果,但欢迎任何编辑。
编辑:它现在也在Kotlin中,所以你可以选择你选择的武器。
发布于 2018-03-05 23:01:27
Parcel位于Android框架中,因此您的测试只能使用Expresso作为Mikhail注释,或者使用Robolectric作为测试运行器。
Robolectric模仿Android.jar并允许这种测试,但考虑到你将对安卓代码进行单元测试……
https://stackoverflow.com/questions/31969224
复制相似问题