Тестирование на Android-устройство: Bundle/Parcelable
Как вы unit test Относительно? Я создал класс Parcelable и написал этот unit test
TestClass test = new TestClass();
Bundle bundle = new Bundle();
bundle.putParcelable("test", test);
TestClass testAfter = bundle.getParcelable("test");
assertEquals(testAfter.getStuff(), event1.getStuff());
Я намеренно пытаюсь пропустить тест, возвратив нулевое значение в createFromParcel()
, но, похоже, это будет успешным. Похоже, он не добирается до тех пор, пока это не понадобится. Как заставить Bundle... упасть?
Ответы
Ответ 1
Я нашел эту ссылку, в которой показано, как вы можете unit test предоставить удачный объект:
http://stuffikeepforgettinghowtodo.blogspot.nl/2009/02/unit-test-your-custom-parcelable.html
Фактически вы можете пропустить Bundle
, если вам не нужно включать его, как это сделал его zorch. Тогда вы получили бы что-то вроде этого:
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);
}
Ответ 2
Вы можете сделать это следующим образом:
//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));