Skip to content

Instantly share code, notes, and snippets.

View Nyame123's full-sized avatar

Nyame Bismark Nyame123

View GitHub Profile
@CustomTestApplication(BaseApplication::class)
interface HiltTestApplication
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@BindValue @JvmField
val analyticsService: AnalyticsService = FakeAnalyticsService()
...
}
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@Module
@InstallIn(SingletonComponent::class)
abstract class TestModule {
@Singleton
@Binds
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [AnalyticsModule::class]
)
abstract class FakeAnalyticsModule {
@Singleton
@Binds
abstract fun bindAnalyticsService(
@Module
@InstallIn(SingletonComponent::class)
abstract class AnalyticsModule {
@Singleton
@Binds
abstract fun bindAnalyticsService(
analyticsServiceImpl: AnalyticsServiceImpl
): AnalyticsService
}
@HiltAndroidTest
class SettingsActivityTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Inject
lateinit var analyticsAdapter: AnalyticsAdapter
@Before
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
class SettingsActivityTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
// Robolectric tests here.
}
// A custom runner to set up the instrumented application class for tests.
class CustomTestRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
}
//gradle file add the testInstrumentationRunner
@HiltAndroidTest
class SettingsActivityTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
// UI tests here.
}
dependencies {
// For Robolectric tests.
testImplementation("com.google.dagger:hilt-android-testing:2.28-alpha")
// ...with Kotlin.
kaptTest("com.google.dagger:hilt-android-compiler:2.28-alpha")
// ...with Java.
testAnnotationProcessor("com.google.dagger:hilt-android-compiler:2.28-alpha")
// For instrumented tests.