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.functional.assisted; 18 19 import static com.google.common.truth.Truth.assertThat; 20 21 import dagger.Binds; 22 import dagger.Component; 23 import dagger.Module; 24 import dagger.assisted.Assisted; 25 import dagger.assisted.AssistedFactory; 26 import dagger.assisted.AssistedInject; 27 import javax.inject.Inject; 28 import org.junit.Test; 29 import org.junit.runner.RunWith; 30 import org.junit.runners.JUnit4; 31 32 @RunWith(JUnit4.class) 33 public final class AssistedFactoryBindsTest { 34 @Component(modules = FooFactoryModule.class) 35 interface ParentComponent { 36 // Test using @Binds where Foo => FooImpl and FooFactory => FooFactoryImpl fooFactory()37 FooFactory fooFactory(); 38 } 39 40 @Module 41 interface FooFactoryModule { 42 @Binds bind(FooFactoryImpl impl)43 FooFactory bind(FooFactoryImpl impl); 44 } 45 46 interface Foo {} 47 48 static final class FooImpl implements Foo { 49 private final Dep dep; 50 private final AssistedDep assistedDep; 51 52 @AssistedInject FooImpl(Dep dep, @Assisted AssistedDep assistedDep)53 FooImpl(Dep dep, @Assisted AssistedDep assistedDep) { 54 this.dep = dep; 55 this.assistedDep = assistedDep; 56 } 57 } 58 59 interface FooFactory { create(AssistedDep assistedDep)60 Foo create(AssistedDep assistedDep); 61 } 62 63 @AssistedFactory 64 interface FooFactoryImpl extends FooFactory { 65 @Override create(AssistedDep assistedDep)66 FooImpl create(AssistedDep assistedDep); 67 } 68 69 static final class AssistedDep {} 70 71 static final class Dep { 72 @Inject Dep()73 Dep() {} 74 } 75 76 @Test testFooFactory()77 public void testFooFactory() { 78 FooFactory fooFactory = DaggerAssistedFactoryBindsTest_ParentComponent.create().fooFactory(); 79 assertThat(fooFactory).isInstanceOf(FooFactoryImpl.class); 80 81 AssistedDep assistedDep = new AssistedDep(); 82 Foo foo = fooFactory.create(assistedDep); 83 assertThat(foo).isInstanceOf(FooImpl.class); 84 85 FooImpl fooImpl = (FooImpl) foo; 86 assertThat(fooImpl.dep).isNotNull(); 87 assertThat(fooImpl.assistedDep).isEqualTo(assistedDep); 88 } 89 } 90