Restore static instances after test completes
PhoneUtilsTest was using reflection to replace the static sPhones in
PhoneFactory to run the test but did not restore the previous value
after the test completed. This caused the mocked test phone to remain
even after the test completed, causing NPEs and other weird behavior.
Test: atest TeleServicesTest
Bug: 228813515
Change-Id: I1bc6ac4fbf3206bce6741be187598a63798d7f1e
diff --git a/tests/src/com/android/phone/PhoneUtilsTest.java b/tests/src/com/android/phone/PhoneUtilsTest.java
index df3a0ac..eb4c248 100644
--- a/tests/src/com/android/phone/PhoneUtilsTest.java
+++ b/tests/src/com/android/phone/PhoneUtilsTest.java
@@ -96,11 +96,13 @@
when(mMockSubscriptionManager.getActiveSubscriptionInfo(
eq(mPhoneAccountHandleIdInteger))).thenReturn(mMockSubscriptionInfo);
when(mMockPhone.getSubId()).thenReturn(mPhoneAccountHandleIdInteger);
- setSinglePhone();
+ Phone[] mPhones = new Phone[] {mMockPhone};
+ replaceInstance(PhoneFactory.class, "sPhones", null, mPhones);
}
@After
public void tearDown() throws Exception {
+ restoreInstance(PhoneFactory.class, "sPhones", null);
}
protected synchronized void replaceInstance(final Class c, final String instanceName,
@@ -117,9 +119,16 @@
field.set(obj, newValue);
}
- private void setSinglePhone() throws Exception {
- Phone[] mPhones = new Phone[] {mMockPhone};
- replaceInstance(PhoneFactory.class, "sPhones", null, mPhones);
+ protected synchronized void restoreInstance(final Class c, final String instanceName,
+ final Object obj) throws Exception {
+ InstanceKey key = new InstanceKey(c, instanceName, obj);
+ if (mOldInstances.containsKey(key)) {
+ Field field = c.getDeclaredField(instanceName);
+ field.setAccessible(true);
+ field.set(obj, mOldInstances.get(key));
+ mOldInstances.remove(key);
+ mInstanceKeys.remove(key);
+ }
}
@Test