我正在使用Dagger 2,并且在为我的类实现测试时,在模块中生成单例提供程序时遇到一些问题.
class SomeContentProvider extends ContentProvider {
// this should be normal foo if run by application,
// or mocked foo if run by tests
@Inject Foo foo;
public Provider() {
Component.getComponent().inject(this);
}
}
@Module
class ProviderModule {
@Singleton
@Provides
Foo providesFoo() {
returns new Foo();
}
}
@Module
class ProviderTestModule {
@Singleton
@Provides
Foo providesFoo() {
returns Mockito.mock(Foo.class);
}
}
public class SomeContentProviderTests extends InstrumentationTestCase {
@Inject Foo foo; // this should be mocked Foo
@Override
public void setUp() throws Exception {
super.setUp();
MockitoAnnotations.initMocks(this);
Component.getTestComponent().inject(this);
}
public void test1() {
// needs new instance of Foo when test1 is run from SomeContentProvider
}
public void test2() {
// needs another new instance of Foo when test2 is run from SomeContentProvider
}
}
所以我有2个问题.
>我无法使用构造函数注入,因为ContentProvider具有默认构造函数. SomeContentProvider如何从测试模块中获取Foo?
>在test1和test2中,如何确保在运行每个测试时创建新的Foo实例?
谢谢!
最佳答案 我发现这篇文章对我特别有用.虽然我遇到的特殊问题更加复杂 – 但我使用相同的想法来模拟模块的提供者.
How do you override a module/dependency in a unit test with Dagger 2.0?