1 /* 2 * Copyright (C) 2016 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.internal.codegen; 18 19 import static com.google.testing.compile.CompilationSubject.assertThat; 20 import static dagger.internal.codegen.Compilers.daggerCompiler; 21 22 import com.google.testing.compile.Compilation; 23 import com.google.testing.compile.JavaFileObjects; 24 import javax.tools.JavaFileObject; 25 import org.junit.Test; 26 import org.junit.runner.RunWith; 27 import org.junit.runners.JUnit4; 28 29 @RunWith(JUnit4.class) 30 public class OptionalBindingTest { 31 @Test provideExplicitOptionalInParent_AndBindsOptionalOfInChild()32 public void provideExplicitOptionalInParent_AndBindsOptionalOfInChild() { 33 JavaFileObject parent = 34 JavaFileObjects.forSourceLines( 35 "test.Parent", 36 "package test;", 37 "", 38 "import dagger.Component;", 39 "import java.util.Optional;", 40 "", 41 "@Component(modules = ParentModule.class)", 42 "interface Parent {", 43 " Optional<String> optional();", 44 " Child child();", 45 "}"); 46 JavaFileObject parentModule = 47 JavaFileObjects.forSourceLines( 48 "test.ParentModule", 49 "package test;", 50 "", 51 "import dagger.Module;", 52 "import dagger.Provides;", 53 "import java.util.Optional;", 54 "", 55 "@Module", 56 "class ParentModule {", 57 " @Provides", 58 " Optional<String> optional() {", 59 " return Optional.of(new String());", 60 " }", 61 "}"); 62 63 JavaFileObject child = 64 JavaFileObjects.forSourceLines( 65 "test.Child", 66 "package test;", 67 "", 68 "import dagger.Subcomponent;", 69 "import java.util.Optional;", 70 "", 71 "@Subcomponent(modules = ChildModule.class)", 72 "interface Child {", 73 " Optional<String> optional();", 74 "}"); 75 JavaFileObject childModule = 76 JavaFileObjects.forSourceLines( 77 "test.ChildModule", 78 "package test;", 79 "", 80 "import dagger.BindsOptionalOf;", 81 "import dagger.Module;", 82 "", 83 "@Module", 84 "interface ChildModule {", 85 " @BindsOptionalOf", 86 " String optionalString();", 87 "}"); 88 89 Compilation compilation = daggerCompiler().compile(parent, parentModule, child, childModule); 90 assertThat(compilation).failed(); 91 assertThat(compilation) 92 .hadErrorContaining("Optional<String> is bound multiple times") 93 .inFile(parent) 94 .onLineContaining("interface Parent"); 95 } 96 } 97