Dagger没有按预期覆盖模块

时间:2015-03-06 10:13:35

标签: java testing dependency-injection mockito dagger

我使用Square的Dagger v1.0.1进行依赖注入,我无法使 overrides = true 按预期工作。

我有一个名为 MyGameTestModule.java 的测试的提供者类:

@Module(
        includes = { BaseModule.class, NetModule.class},
        injects = { MyGame.class, MyManager.class },
        overrides = true
)
public class MyGameTestModule {

    // ...

    @Provides
    @Singleton
    DummyInterface provideDummyInterface() {
        return new DummyInterface() {
            @Override
            public Bar getBar() {
                // return actual Bar
            }
        };
    }
}

我有一个名为 MyManagerTest.java 的测试:

public class MyManagerTest {
    @Inject
    public MyManager myManager;

    // ...

    @Before
    public void setup() {
        ObjectGraph objectGraph = ObjectGraph.create(new TestModule());
        objectGraph.inject(this);
    }

    @Module(
        includes = {MyGameTestModule.class}, 
        injects = {MyManagerTest.class}, 
        overrides = true
    )
    public static class TestModule {
        @Provides
        @Singleton
        DummyInterface provideDummyInterface() {
            return new DummyInterface() {
                @Override
                public Bar getBar() {
                    // return mocked Bar
                }
            };
        }
    }     
}

但是当我运行我的测试时,Dagger会抛出这样的异常:

  

java.lang.IllegalArgumentException:Duplicate:       com.foo.DummyInterface com.foo.MyManagerTest $ TestModule.provideDummyInterface()       com.foo.DummyInterface com.foo.MyGameTestModule.provideDummyInterface()at   dagger.internal.UniqueMap.put(UniqueMap.java:29)at   dagger.internal.plugins.reflect.ReflectiveModuleAdapter.handleBindings(ReflectiveModuleAdapter.java:104)     在   dagger.internal.plugins.reflect.ReflectiveModuleAdapter.getBindings(ReflectiveModuleAdapter.java:89)     在   dagger.ObjectGraph $ DaggerObjectGraph.makeGraph(ObjectGraph.java:174)     在   dagger.ObjectGraph $ DaggerObjectGraph.access $ 000(ObjectGraph.java:132)     在dagger.ObjectGraph.create(ObjectGraph.java:129)at   com.foo.MyManagerTest.setup(MyManagerTest.java:38)

我错过了什么吗?它是否应该使用"覆盖= true" 提供给模块来覆盖MyGameTestModule中的DummyInterface?

提前致谢。

1 个答案:

答案 0 :(得分:0)

addsTo中使用includes代替TestModule

@Module(
    addsTo = {MyGameTestModule.class}, 
    injects = {MyManagerTest.class}, 
    overrides = true
)
public static class TestModule {
}

使用ObjectGraphMyGameTestModule创建TestModule

ObjectGraph.create(new MyGameTestModule(), new TestModule());