xref: /aosp_15_r20/external/dagger2/javatests/dagger/functional/kotlinsrc/binds/RecursiveBindsTest.kt (revision f585d8a307d0621d6060bd7e80091fdcbf94fe27)
1 /*
2  * Copyright (C) 2023 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.functional.kotlinsrc.binds
18 
19 import com.google.common.truth.Truth.assertThat
20 import dagger.Binds
21 import dagger.Component
22 import dagger.Module
23 import javax.inject.Inject
24 import javax.inject.Provider
25 import javax.inject.Singleton
26 import org.junit.Test
27 import org.junit.runner.RunWith
28 import org.junit.runners.JUnit4
29 
30 // This is a regression test for b/267223822 where a scoped @Binds used in a cycle caused problems
31 // in fastInit mode.
32 @RunWith(JUnit4::class)
33 class RecursiveBindsTest {
34 
35   interface Foo {}
36 
37   class FooImpl internal @Inject constructor(@SuppressWarnings("unused") provider: Provider<Foo>) :
38     Foo {}
39 
40   @Module
41   interface FooModule {
42     // This binding must be scoped to create the cycle. Otherwise without a scope, the generated
43     // code just doesn't have a field for this @Binds because we can directly use FooImpl's
44     // provider as they are equivalent.
bindFoonull45     @Binds @Singleton fun bindFoo(impl: FooImpl): Foo
46   }
47 
48   @Component(modules = FooModule::class)
49   @Singleton
50   interface TestSingletonComponent {
51     // We get the impl here to create a cycle where the impl factory needs to be delegated.
52     // That way the scoped binds (which does something like DoubleCheck.provider(implFactory)) is
53     // the one that would fail if it wasn't delegated properly.
54     fun getFooImplProvider(): Provider<FooImpl>
55   }
56 
57   @Test
testnull58   fun test() {
59     // Technically the NPE would happen when just initializing the component.
60     assertThat(DaggerRecursiveBindsTest_TestSingletonComponent.create().getFooImplProvider().get())
61       .isNotNull()
62   }
63 }
64