1 /* 2 * Copyright (C) 2020 The Dagger Authors. 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 dagger.hilt.android.internal.testing; 18 19 import java.lang.reflect.InvocationTargetException; 20 21 /** Stores the {@link TestComponentData} for a Hilt test class. */ 22 public abstract class TestComponentDataSupplier { 23 24 /** Returns a {@link TestComponentData}. */ get()25 protected abstract TestComponentData get(); 26 get(Class<?> testClass)27 static TestComponentData get(Class<?> testClass) { 28 String generatedClassName = getEnclosedClassName(testClass) + "_TestComponentDataSupplier"; 29 try { 30 return Class.forName(generatedClassName) 31 .asSubclass(TestComponentDataSupplier.class) 32 .getDeclaredConstructor() 33 .newInstance() 34 .get(); 35 } catch (ClassNotFoundException 36 | NoSuchMethodException 37 | IllegalAccessException 38 | InstantiationException 39 | InvocationTargetException e) { 40 throw new RuntimeException( 41 String.format( 42 "Hilt test, %s, is missing generated file: %s. Check that the test class is " 43 + " annotated with @HiltAndroidTest and that the processor is running over your" 44 + " test.", 45 testClass.getSimpleName(), 46 generatedClassName), 47 e); 48 } 49 } 50 getEnclosedClassName(Class<?> testClass)51 private static String getEnclosedClassName(Class<?> testClass) { 52 StringBuilder sb = new StringBuilder(); 53 Class<?> currClass = testClass; 54 while (currClass != null) { 55 Class<?> enclosingClass = currClass.getEnclosingClass(); 56 if (enclosingClass != null) { 57 sb.insert(0, "_" + currClass.getSimpleName()); 58 } else { 59 sb.insert(0, currClass.getCanonicalName()); 60 } 61 currClass = enclosingClass; 62 } 63 return sb.toString(); 64 } 65 } 66