Androidunit testing:Bundle / Parcelable

你如何testingParcelable? 我创build了一个Parcelable类,并写了这个unit testing

TestClass test = new TestClass(); Bundle bundle = new Bundle(); bundle.putParcelable("test", test); TestClass testAfter = bundle.getParcelable("test"); assertEquals(testAfter.getStuff(), event1.getStuff()); 

我特意尝试通过在createFromParcel()返回null来尝试失败,但似乎成功了。 它看起来好像没有被包裹,直到需要它。 我如何强制捆绑…捆绑?

我发现这个链接显示如何可以unit testing一个parcelable对象: http ://stuffikeepforgettinghowtodo.blogspot.nl/2009/02/unit-test-your-custom-parcelable.html

如果你真的不需要像Zorch提出的build议那样包括它,你实际上可以跳过Bundle 。 你会得到这样的东西:

 public void testTestClassParcelable(){ TestClass test = new TestClass(); // 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: TestClass createdFromParcel = TestClass.CREATOR.createFromParcel(parcel); assertEquals(test, createdFromParcel); } 

你可以这样做:

 //Create parcelable object and put to Bundle Question q = new Question(questionId, surveyServerId, title, type, answers); Bundle b = new Bundle(); b.putParcelable("someTag", q); //Save bundle to parcel Parcel parcel = Parcel.obtain(); b.writeToParcel(parcel, 0); //Extract bundle from parcel parcel.setDataPosition(0); Bundle b2 = parcel.readBundle(); b2.setClassLoader(Question.class.getClassLoader()); Question q2 = b2.getParcelable("someTag"); //Check that objects are not same and test that objects are equal assertFalse("Bundle is the same", b2 == b); assertFalse("Question is the same", q2 == q); assertTrue("Questions aren't equal", q2.equals(q));