我想将我的领域管理器用于单元测试模块。 我做到了
@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/