如何在 Jetpack 可组合测试中获取字符串资源

Sha*_*auf 12 android android-testing android-jetpack android-jetpack-compose

我们可以通过 stringResource 来获取 Composable 中的字符串资源,例如

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

但是我们如何在可组合测试中获取这个字符串资源。

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

VIG*_*ESH 19

您仍然可以使用androidx.test.platform.app.InstrumentationRegistrycomposeapp 中的资源来获取资源。

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


Run Code Online (Sandbox Code Playgroud)


jor*_*uke 6

通过创建撰写规则createAndroidComposeRule,然后您将能够访问activity.getString()方法

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

val activity = composeTestRule.activity

@Test
fun testDisplayAndClickable() {
    val home = composeTestRule.activity.getString(R.string.home)
}
Run Code Online (Sandbox Code Playgroud)