我们可以像这样通过stringResource获取Composable中的字符串资源
@Composable
fun Heading(
@StringRes textResource: Int
) {
Text(
text = stringResource(id = textResource),
color = colorBlack,
)
}
但是我们如何在可组合测试中获取这个字符串资源。
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()
}
}
您仍然可以使用
androidx.test.platform.app.InstrumentationRegistry
在 composeapp 中获取资源。
val context: Context = InstrumentationRegistry.getInstrumentation().getTargetContext()
var string2 = context.resources.getString(R.string.hello_world)
通过
createAndroidComposeRule
创建撰写规则,然后您就可以访问activity.getString()
方法
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
val activity = composeTestRule.activity
@Test
fun testDisplayAndClickable() {
val home = composeTestRule.activity.getString(R.string.home)
}
我不确定是否有更好的方法,但你可以执行以下操作:
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()
}
}
使用已接受答案的方法获取
Context
,您还可以在Kotlin中创建扩展方法。
val context: Context = InstrumentationRegistry.getInstrumentation().targetContext
fun SemanticsNodeInteractionsProvider.onNodeWithText(
@StringRes resId: Int,
substring: Boolean = false,
ignoreCase: Boolean = false,
useUnmergedTree: Boolean = false
): SemanticsNodeInteraction =
onNode(
hasText(
context.resources.getString(resId),
substring,
ignoreCase,
),
useUnmergedTree)
然后可以像任何其他语义匹配器一样使用
composeTestRule.onNodeWithContentDescription(R.string.some_text).performClick()