Neil Fuller | 2c6d510 | 2019-11-29 09:02:39 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package android.app.timezonedetector; |
| 18 | |
| 19 | import static org.junit.Assert.assertEquals; |
| 20 | |
| 21 | import android.os.Parcel; |
| 22 | import android.os.Parcelable; |
| 23 | |
| 24 | import java.lang.reflect.Field; |
| 25 | |
| 26 | /** Utility methods related to {@link Parcelable} objects used in several tests. */ |
| 27 | public final class ParcelableTestSupport { |
| 28 | |
| 29 | private ParcelableTestSupport() {} |
| 30 | |
| 31 | /** Returns the result of parceling and unparceling the argument. */ |
| 32 | @SuppressWarnings("unchecked") |
| 33 | public static <T extends Parcelable> T roundTripParcelable(T parcelable) { |
| 34 | Parcel parcel = Parcel.obtain(); |
| 35 | parcel.writeTypedObject(parcelable, 0); |
| 36 | parcel.setDataPosition(0); |
| 37 | |
| 38 | Parcelable.Creator<T> creator; |
| 39 | try { |
| 40 | Field creatorField = parcelable.getClass().getField("CREATOR"); |
| 41 | creator = (Parcelable.Creator<T>) creatorField.get(null); |
| 42 | } catch (NoSuchFieldException | IllegalAccessException e) { |
| 43 | throw new AssertionError(e); |
| 44 | } |
| 45 | T toReturn = parcel.readTypedObject(creator); |
| 46 | parcel.recycle(); |
| 47 | return toReturn; |
| 48 | } |
| 49 | |
| 50 | public static <T extends Parcelable> void assertRoundTripParcelable(T instance) { |
| 51 | assertEquals(instance, roundTripParcelable(instance)); |
| 52 | } |
| 53 | } |