google / dagger

A fast dependency injector for Android and Java.
https://dagger.dev
Apache License 2.0
17.36k stars 2k forks source link

[Hilt] FR: Create a HiltComponentActivity artifact #3394

Open JoseAlcerreca opened 2 years ago

JoseAlcerreca commented 2 years ago

When creating Compose tests, it's very common to start an empty ComponentActivity so that you can set the content later:

@HiltAndroidTest
class NavigationTest {

    @get:Rule(order = 0)
    var hiltRule = HiltAndroidRule(this)

    @get:Rule(order = 1)
    val composeTestRule = createAndroidComposeRule<ComponentActivity>()

    @Test
    fun test1() {
        composeTestRule.setContent {
            MainNavigation()
        }
        composeTestRule.onNodeWithText("One")
    }
}

However, this test crashes* because ComponentActivity is not annotated for Hilt. The workaround is to create a HiltComponentActivity in debug/ and add it to the manifest, which is not ideal.

We solved a very similar issue for Compose Testing already with theui-test-manifest artifact: https://maven.google.com/web/index.html?q=manifest#androidx.compose.ui:ui-test-manifest:1.2.0-beta01

which is installed in the debug sourceset:

debugImplementation("androidx.compose.ui:ui-test-manifest:$compose_version")

For consistency, the new artifact could be called ui-test-hilt-manifest.


nalanulusoy commented 1 year ago

Hi I take it same issue This issue reason composeTestRule.setContent { MainNavigation() } your function block MainNavigation() inside I assume that your code has viewModel = hiltViewModel(). compose navigation working issue is not generate hiltviewmodel() when test runtime . In mycase unfortunatally not working current version .

implementation "androidx.hilt:hilt-navigation-compose:$hiltComposeNavigation"

WingEraser commented 1 year ago

I managed to solve this by these two links:

Chang-Eric commented 1 year ago

Just leaving some info. We have wanted to create an convenient Hilt test activity but have been blocked on https://b.corp.google.com/issues/127986458. I don't think we're keen on using the workaround for this though as this is a convenience thing (since you can always define your own simple Hilt test activity) and not actually blocking.

trietbui85 commented 2 months ago

I cannot access https://b.corp.google.com/issues/127986458 since is private. So what's its status?

JoseAlcerreca commented 2 months ago

https://issuetracker.google.com/127986458