'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 1:[1]
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)
}
Solution 2:[2]
I'm not sure if there's a better way, but you can do the following:
class HeadingTest {
@get:Rule
val composeTestRule = createComposeRule()
@ExperimentalComposeUiApi
@Test
fun headingTest() {
val textId = R.string.some_text
var string = ""
// Start the app
composeTestRule.setContent {
string = stringResource(id = textId)
AppTheme {
// In Compose world
Heading(textResource = textId)
}
}
composeTestRule.onNodeWithText(string).assertExists()
}
}
Solution 3:[3]
You can get an activity instance if you initiate AndroidComposeTestRule
class HeadingTest {
@get:Rule
val androidComposeTestRule = createAndroidComposeRule<ComponentActivity>()
@ExperimentalComposeUiApi
@Test
fun headingTest() {
// Start the app
androidComposeTestRule.setContent {
AppTheme {
// In Compose world
Heading(textResource = R.string.some_text)
}
}
//Call getString() from activity instance
androidComposeTestRule.onNodeWithText(androidComposeTestRule.activity.getString(R.string.some_text))
.assertExists()
}
}
Solution 4:[4]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jorieitomuke |
Solution 2 | nglauber |
Solution 3 | Shahab Rauf |
Solution 4 | VIGNESH |