Skip to content

Instantly share code, notes, and snippets.

Avatar

kozmi55

  • Instructure
View GitHub Profile
View TestApplicationModule.kt
@Module
class TestApplicationModule(
private val userRepository: UserRepository = FakeUserRepository(),
private val detailsRepository: DetailsRepository = FakeDetailsRepository()) {
@Provides
@Singleton
fun provideUserRepository(): UserRepository {
return userRepository
}
View UserListFragmentTest.kt
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
TestInjector(TestApplicationModule(mockUserRepository)).inject()
}
View TestInjector.kt
class TestInjector(private val testApplicationModule: TestApplicationModule) {
fun inject() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val app = instrumentation.targetContext.applicationContext as TestApplication
DaggerTestApplicationComponent
.builder()
.appModule(testApplicationModule)
.create(app)
View UserListFragmentTest.kt
@RunWith(AndroidJUnit4::class)
class UserListFragmentTest {
@Rule
@JvmField
var activityRule = ActivityTestRule(MainActivity::class.java, true, false)
@Mock
private lateinit var mockUserRepository: UserRepository
View build.gradle
android {
compileSdkVersion 27
buildToolsVersion "27.0.3"
defaultConfig {
applicationId "com.example.tamaskozmer.kotlinrxexample"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "com.example.tamaskozmer.kotlinrxexample.testutil.CustomTestRunner"
View CustomTestRunner.kt
class CustomTestRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
return super.newApplication(cl, TestApplication::class.java.name, context)
}
}
View TestApplication.kt
class TestApplication : Application(), HasSupportFragmentInjector {
@Inject
lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>
override fun supportFragmentInjector() = fragmentInjector
}
View CustomApplication.kt
class CustomApplication : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerApplicationComponent.builder().create(this)
}
}
View UserListFragmentTest.kt
@RunWith(AndroidJUnit4::class)
class UserListFragmentTest {
@Rule
@JvmField
var activityRule = ActivityTestRule(MainActivity::class.java, true, false)
@Mock
private lateinit var mockUserRepository: UserRepository
View CustomApplication.kt
class CustomApplication : Application() {
lateinit var component: ApplicationComponent
override fun onCreate() {
super.onCreate()
component = DaggerApplicationComponent
.builder()
.applicationModule(ApplicationModule(this))