-
-
Save lucamtudor/e665908462f76c2ce553a18bca1579be 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
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
<!-- **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> |
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
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() | |
} | |
} |
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
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