Skip to content

Instantly share code, notes, and snippets.

@SabagRonen
Created April 28, 2018 08:02
Show Gist options
  • Save SabagRonen/b476021a779f08416f103bda972ca09d to your computer and use it in GitHub Desktop.
Save SabagRonen/b476021a779f08416f103bda972ca09d to your computer and use it in GitHub Desktop.
Mock Activity Injector
@RunWith(AndroidJUnit4::class)
class MainViewTests {
val mockUserAction = mock(MainContract.UserAction::class.java)
@get:Rule
val activityTestRule = object : ActivityTestRule<MainActivity>(MainActivity::class.java, true, true) {
override fun beforeActivityLaunched() {
super.beforeActivityLaunched()
val myApp = InstrumentationRegistry.getTargetContext().applicationContext as MyApp
myApp.dispatchingActivityInjector = createFakeFragmentInjector<MainFragment> {
userAction = mockUserAction
// mock only userAction and use the original otherMemberThatIDoNotWantToMock
// otherMemberThatIDoNotWantToMock = ...
}
}
}
}
inline fun <reified T : Activity> createFakeActivityInjector(crossinline block : T.() -> Unit)
: DispatchingAndroidInjector<Activity> {
val myApp = InstrumentationRegistry.getTargetContext().applicationContext as MyApp
val originalDispatchingActivityInjector = myApp.dispatchingActivityInjector
val injector = AndroidInjector<Activity> { instance ->
originalDispatchingActivityInjector.inject(activity)
if (instance is T) {
instance.block()
}
}
val factory = AndroidInjector.Factory<Activity> { injector }
val map = mapOf(Pair<Class <out Activity>, Provider<Factory<out Activity>>>(T::class.java, Provider { factory }))
return DispatchingAndroidInjector_Factory.newDispatchingAndroidInjector(map)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment