Last active
February 27, 2019 17:13
-
-
Save CodyDunlap/3baa3e06f421fdc90c086e49448ef1a2 to your computer and use it in GitHub Desktop.
Dagger 2 Test Component Injection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Config(application = TestApp::class) | |
class AccountServiceUnitTest { | |
@Before | |
fun setup() { | |
val testComponent = DaggerTestAppComponent.builder().build() | |
testComponent.inject(this) | |
} | |
//perform tests | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TestApp : App() { | |
override fun initDagger(app: App): AppComponent { | |
return DaggerTestAppComponent.builder().build() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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