Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    }
}
like image 567
Shahab Rauf Avatar asked Dec 01 '25 23:12

Shahab Rauf


2 Answers

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)
    


like image 123
VIGNESH Avatar answered Dec 04 '25 12:12

VIGNESH


Create compose rule via createAndroidComposeRule and then you will be able to access activity.getString() method

@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()

val activity = composeTestRule.activity

@Test
fun testDisplayAndClickable() {
    val home = composeTestRule.activity.getString(R.string.home)
}
like image 40
adwardwo1f Avatar answered Dec 04 '25 12:12

adwardwo1f



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!