android - Dagger 2 如何将对象注入(inject)测试

标签 android dependency-injection dagger-2 daggermock

我想将我的领域管理器用于单元测试模块。 我做到了

@Singleton
@Component(modules = {
        TestApplicationModule.class,
        AndroidSupportInjectionModule.class,
        TestStoreDataModule.class,
        TestUtilsModule.class})
public interface AppComponentTest extends AppComponent {

    @Component.Builder
    interface Builder {

        @BindsInstance
        AppComponentTest.Builder application(Application application);

        AppComponentTest build();
    }
}

然后我要实现

@RunWith(RobolectricTestRunner.class)
@Config(application = TestVerioriApplication.class, sdk=27)
public class BaseVerificationQuestionnaireFragmentTest {

    @Inject
    RealmManager realmManager;
}

但 realmManager 为空。如何使用 dagger 2 编写简单的模块测试?我使用了 dagger-mock 但它没有帮助。我的模块包含

@Module(includes = StoreDataModule.class)
public class TestStoreDataModule {

    @Provides
    @Singleton
    public static RealmConfiguration provideRealmConfiguration(RealmConstants realmConstants) {
        return new RealmConfiguration.Builder()
                .name(realmConstants.getName())
                .encryptionKey("Implement this key".getBytes())
                .schemaVersion(realmConstants.getSchemaVersion())
                .build();
    }

    @Provides
    @Singleton
    public static RealmManager provideRealmManager(RealmConfiguration realmConfiguration, SchedulerProvider schedulerProvider) {
        return new RealmManager(realmConfiguration, schedulerProvider);
    }

}

我尝试了所有来自谷歌的东西,但我不知道如何从图形中注入(inject)对象。

最佳答案

重写您的 Application 类,您将在其中用您的 TestComponent 替换 Dagger 组件实例。然后通过覆盖需要添加测试应用程序的 AndroidJUnitRunner 类来创建您自己的测试运行器:

class TestRunner : AndroidJUnitRunner() {
   @Throws(InstantiationException::class,IllegalAccessException::class,ClassNotFoundException::class)
 override fun newApplication(cl:ClassLoader,className:String, context:Context):Application {
        return super.newApplication(cl, TestApplication::class.java.name, context)
  }
}

接下来在 build.gradle 文件中注册你的运行者:

testInstrumentationRunner“com.test.YourTestRunner”

现在您只需在测试组件中替换要在测试中更改的模块的实现即可。

关于android - Dagger 2 如何将对象注入(inject)测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53118205/

相关文章:

java - HK2 相当于 Guice 中的 @Provides for Jersey 2

android - Dagger2 如何执行具有默认构造函数依赖性的构造函数注入(inject)

java - 如何在 Spring 应用程序上下文中扩展已定义的列表和映射?

android - Kotlin 多平台用于开发 Mobile SDK?

android - NestedScrollView 无法使用 match_parent 高度子项滚动

android - libz.so.1 : cannot open shared object file

java - Guice 在 AbstractModule 之间合并集合

Android Mockito kotlin.UninitializedPropertyAccessException : lateinit property dataManager has not been initialized

android - 找不到带有 Dagger 2 的符号 ViewModel

java - 在 SoundCloud Android 应用程序中使用 Facebook 和 Google Plus 登录