Mockito的匕首注射

时间:2017-11-15 22:41:54

标签: android unit-testing mockito dagger-2

我有一个关于如何让我的仪器测试与我现有的dagger项目一起工作的问题。

我有这些课程

class Foo {
    @Inject Bar bar;

    @Inject
    Foo() {
        DaggerComponent.getComponent().inject(this);
    }
}

class Bar {
    @Inject DummyObj dummy;
    @Inject Context context;

    @Inject
    Bar() {
        DaggerComponent.getComponent().inject(this);
    }
}

@Module
public class RealModule {
     @Provides
     public providesDummyObj(Context context) {
         return new DummyObj(context);
     }
}

上面的代码不完整,但它基本上是使用应用程序中的RealModule。它运行正常。

但是现在我想要一个从Foo执行测试的检测测试用例,但是使用Mocked上下文和DummyObj,所以Foo和Bar类会自动获取模拟对象;而不是传递模拟对象?

class FooTest extends InstrumentationTest {
    @Mock DummyObj mDummyObj;
    @Mock Context context;
    @Inject Bar bar;

    @Override
    setup() throws Exception {
        DaggerComponent.getComponent().inject(this);
        MockitoAnnotation.initMocks(this);

        doReturn("test").when(mDummyObj).doSomething();
    }
}

有没有办法覆盖我的检测测试中的dummycontext来提供实际模拟的对象?

帮助表示赞赏。谢谢!

0 个答案:

没有答案