xref: /aosp_15_r20/external/dagger2/java/dagger/hilt/android/testing/HiltTestApplication.java (revision f585d8a307d0621d6060bd7e80091fdcbf94fe27)
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.testing;
18 
19 import androidx.multidex.MultiDexApplication;
20 import dagger.hilt.android.internal.testing.TestApplicationComponentManager;
21 import dagger.hilt.android.internal.testing.TestApplicationComponentManagerHolder;
22 import dagger.hilt.internal.GeneratedComponentManager;
23 
24 /**
25  * An application that can be used for Android instrumentation or Robolectric tests using Hilt.
26  */
27 public final class HiltTestApplication extends MultiDexApplication
28     implements GeneratedComponentManager<Object>, TestApplicationComponentManagerHolder {
29 
30   // This field is initialized lazily to avoid pulling the generated component into the main dex. We
31   // could possibly avoid this by class loading TestComponentDataSupplier lazily rather than in the
32   // TestApplicationComponentManager constructor.
33   private volatile TestApplicationComponentManager componentManager;
34   private final Object componentManagerLock = new Object();
35 
36   @Override
componentManager()37   public final GeneratedComponentManager<Object> componentManager() {
38     if (componentManager == null) {
39       synchronized (componentManagerLock) {
40         if (componentManager == null) {
41           componentManager = new TestApplicationComponentManager(this);
42         }
43       }
44     }
45     return componentManager;
46   }
47 
48   @Override
generatedComponent()49   public final Object generatedComponent() {
50     return componentManager().generatedComponent();
51   }
52 }
53