Skip to content

Instantly share code, notes, and snippets.

@CodyDunlap
Last active February 27, 2019 17:13
Show Gist options
  • Save CodyDunlap/3baa3e06f421fdc90c086e49448ef1a2 to your computer and use it in GitHub Desktop.
Save CodyDunlap/3baa3e06f421fdc90c086e49448ef1a2 to your computer and use it in GitHub Desktop.
Dagger 2 Test Component Injection
@Config(application = TestApp::class)
class AccountServiceUnitTest {
@Before
fun setup() {
val testComponent = DaggerTestAppComponent.builder().build()
testComponent.inject(this)
}
//perform tests
}
@RunWith(RobolectricTestRunner::class)
@Config(application = TestApp::class)
class ActivityUnitTest {
@Before
fun setup() {
val testApp = (RuntimeEnvironment.application as TestApp)
val testComponent = testApp.appComponent as TestAppComponent
testComponent.inject(this)
}
}
lateinit var appComponent: AppComponent
companion object {
lateinit var instance : App
private set
}
override fun onCreate() {
super.onCreate()
instance = this
appComponent = initDagger(this)
}
open fun initDagger(app: App): AppComponent {
return DaggerAppComponent.builder().appModule(AppModule(app)).build()
}
class TestApp : App() {
override fun initDagger(app: App): AppComponent {
return DaggerTestAppComponent.builder().build()
}
}
@Singleton
@Component(modules = [
TestServicesModule::class,
TestRepositoriesModule::class,
TestPreferencesModule::class
])
interface TestAppComponent : AppComponent {
//services
fun inject(target: AccountServiceUnitTest)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment