Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Last active October 21, 2020 12:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mitchtabian/b7bb933d2f1fb5262f9d6b24b247a0ab to your computer and use it in GitHub Desktop.
Save mitchtabian/b7bb933d2f1fb5262f9d6b24b247a0ab to your computer and use it in GitHub Desktop.
Enable Fragment constructor injection for instrumentation tests when using Hilt. This is a modified version of https://github.com/android/architecture-samples/blob/dev-hilt/app/src/androidTest/java/com/example/android/architecture/blueprints/todoapp/HiltExt.kt
<!-- **NOTE** This must be in /debug/ -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.codingwithmitch.daggerhiltplayground">
<application>
<activity
android:name="com.codingwithmitch.daggerhiltplayground.HiltTestActivity"
android:exported="false" />
</application>
</manifest>
inline fun <reified T : Fragment> launchFragmentInHiltContainer(
fragmentArgs: Bundle? = null,
@StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme,
factory: FragmentFactory,
crossinline action: Fragment.() -> Unit = {}
) {
val startActivityIntent = Intent.makeMainActivity(
ComponentName(
ApplicationProvider.getApplicationContext(),
HiltTestActivity::class.java
)
).putExtra(EmptyFragmentActivity.THEME_EXTRAS_BUNDLE_KEY, themeResId)
ActivityScenario.launch<HiltTestActivity>(startActivityIntent).onActivity { activity ->
activity.supportFragmentManager.fragmentFactory = factory
val fragment: Fragment = activity.supportFragmentManager.fragmentFactory.instantiate(
Preconditions.checkNotNull(T::class.java.classLoader),
T::class.java.name
)
fragment.arguments = fragmentArgs
activity.supportFragmentManager
.beginTransaction()
.add(android.R.id.content, fragment, "")
.commitNow()
fragment.action()
}
}
import androidx.appcompat.app.AppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
// **NOTE** This must be in /debug/
@AndroidEntryPoint
class HiltTestActivity : AppCompatActivity()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment