1 /* 2 * Copyright (C) 2020 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 android.content.Context; 20 21 import com.android.launcher3.util.MainThreadInitializedObject.ObjectProvider; 22 import com.android.launcher3.util.ResourceBasedOverride; 23 import com.android.launcher3.util.ResourceBasedOverride.Overrides; 24 25 import org.robolectric.annotation.Implementation; 26 import org.robolectric.annotation.Implements; 27 import org.robolectric.shadow.api.Shadow; 28 import org.robolectric.util.ReflectionHelpers.ClassParameter; 29 30 import java.util.HashMap; 31 import java.util.Map; 32 33 /** 34 * Shadow for {@link Overrides} to provide custom overrides for test 35 */ 36 @Implements(value = Overrides.class, isInAndroidSdk = false) 37 public class ShadowOverrides { 38 39 private static Map<Class, ObjectProvider> sProviderMap = new HashMap<>(); 40 41 @Implementation getObject( Class<T> clazz, Context context, int resId)42 public static <T extends ResourceBasedOverride> T getObject( 43 Class<T> clazz, Context context, int resId) { 44 ObjectProvider<T> provider = sProviderMap.get(clazz); 45 if (provider != null) { 46 return provider.get(context); 47 } 48 return Shadow.directlyOn(Overrides.class, "getObject", 49 ClassParameter.from(Class.class, clazz), 50 ClassParameter.from(Context.class, context), 51 ClassParameter.from(int.class, resId)); 52 } 53 setProvider(Class<T> clazz, ObjectProvider<T> provider)54 public static <T> void setProvider(Class<T> clazz, ObjectProvider<T> provider) { 55 sProviderMap.put(clazz, provider); 56 } 57 clearProvider()58 public static void clearProvider() { 59 sProviderMap.clear(); 60 } 61 } 62