1 /* 2 * Copyright (C) 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 com.android.launcher3.shadows; 18 19 import static org.robolectric.shadow.api.Shadow.invokeConstructor; 20 import static org.robolectric.util.ReflectionHelpers.ClassParameter.from; 21 22 import com.android.launcher3.util.MainThreadInitializedObject; 23 import com.android.launcher3.util.MainThreadInitializedObject.ObjectProvider; 24 25 import org.robolectric.annotation.Implementation; 26 import org.robolectric.annotation.Implements; 27 import org.robolectric.annotation.RealObject; 28 29 import java.util.ArrayList; 30 import java.util.Collections; 31 import java.util.Set; 32 import java.util.WeakHashMap; 33 34 /** 35 * Shadow for {@link MainThreadInitializedObject} to provide reset functionality for static sObjects 36 */ 37 @Implements(value = MainThreadInitializedObject.class, isInAndroidSdk = false) 38 public class ShadowMainThreadInitializedObject { 39 40 // Keep reference to all created MainThreadInitializedObject so they can be cleared after test 41 private static Set<MainThreadInitializedObject> sObjects = 42 Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<>())); 43 44 @RealObject private MainThreadInitializedObject mRealObject; 45 46 @Implementation __constructor__(ObjectProvider provider)47 protected void __constructor__(ObjectProvider provider) { 48 invokeConstructor(MainThreadInitializedObject.class, mRealObject, 49 from(ObjectProvider.class, provider)); 50 sObjects.add(mRealObject); 51 } 52 53 /** 54 * Resets all the initialized sObjects to be null 55 */ resetInitializedObjects()56 public static void resetInitializedObjects() { 57 for (MainThreadInitializedObject object : new ArrayList<>(sObjects)) { 58 object.initializeForTesting(null); 59 } 60 } 61 } 62