androidandroid-jetpack-composeandroid-jetpackandroid-testing

How can I get string resource in Jetpack composable test


We can get the string resource in Composable through stringResource like

@Composable
fun Heading(
    @StringRes textResource: Int
) {
    Text(
        text = stringResource(id = textResource),
        color = colorBlack,
    )
}

But how can we get this string resource in composable test.

class HeadingTest {

    @get:Rule
    val composeTestRule = createComposeRule()

    @ExperimentalComposeUiApi
    @Test
    fun headingTest() {
        // Start the app
        composeTestRule.setContent {
            AppTheme {
                // In Compose world
                Heading(textResource = R.string.some_text)
            }
        }

        //How can I access string resource here
        composeTestRule.onNodeWithText(???).assertExists()
    }
}

Solution

  • Still you can use androidx.test.platform.app.InstrumentationRegistry to get resource in composeapp.

        val context: Context = InstrumentationRegistry.getInstrumentation().getTargetContext()
        var string2 = context.resources.getString(R.string.hello_world)