Skip to content

Instantly share code, notes, and snippets.

@SabagRonen
Last active August 31, 2019 15:59
Show Gist options
  • Save SabagRonen/ada832a7fb8715db7877131135da6269 to your computer and use it in GitHub Desktop.
Save SabagRonen/ada832a7fb8715db7877131135da6269 to your computer and use it in GitHub Desktop.
Fragment espresso with Dagger
inline fun <reified F : Fragment> createFakeFragmentInjector(crossinline block : F.() -> Unit)
: DispatchingAndroidInjector<Any> {
val myApp = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as MyApp
val originalDispatchingActivityInjector = myApp.dispatchingActivityInjector
var originalFragmentInjector: AndroidInjector<Any>? = null
val fragmentInjector = AndroidInjector<Fragment> { fragment ->
originalFragmentInjector?.inject(fragment)
if (fragment is F) {
fragment.block()
}
}
val fragmentFactory = Factory<Fragment> { fragmentInjector }
val fragmentMap = mapOf(Pair<Class <*>, Provider<Factory<*>>>(F::class.java, Provider { fragmentFactory }))
val activityInjector = AndroidInjector<Activity> { activity ->
originalDispatchingActivityInjector.inject(activity)
if (activity is MainActivity) {
originalFragmentInjector = activity.androidInjector()
activity.fragmentInjector = DispatchingAndroidInjector_Factory.newInstance(fragmentMap, emptyMap())
}
}
val activityFactory = Factory<Activity> { activityInjector }
val activityMap = mapOf(Pair<Class <*>, Provider<Factory<*>>>(MainActivity::class.java, Provider { activityFactory }))
return DispatchingAndroidInjector_Factory.newInstance(activityMap, emptyMap())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment