The app supports 2 locales. During instrumentation or UI test, I want to test with a specific language (such as EN
). Referring 6629458, I made a function for changing the locale in kotlin:
private fun setLocale(language: String, country: String) {
val context = InstrumentationRegistry.getInstrumentation().context
val locale = Locale(language, country)
// here we update locale for date formatters
Locale.setDefault(locale)
// here we update locale for app resources
val res: Resources = context.getResources()
val config: Configuration = res.configuration
config.locale = locale
res.updateConfiguration(config, res.displayMetrics)
}
It can be called inside a UT test function body:
@Test
fun uiTest () {
composeTestRule.setContent {
...
}
setLocale("en", "EN")
...
}
However, the locale is not set to English but depending on the default setting of my testing Android device. Is there any clue for this (function is call without error but the locale is NOT changed as expected)?
Another question was also posted but it is not for UI test.
Use stringResource()
inside UI test function's composeTestRule.setContent{}
body then the test string will be changed dynamically depending on the device's system local setting.
@Test
fun uiTest() {
var string1 = ""
var string2 = ""
var string3 = ""
composeTestRule.setContent {
string1 = stringResource(id = R.string.string1)
string2 = stringResource(id = R.string.string2)
string3 = stringResource(id = R.string.string3)
AppTheme {
TestComponent()
}
}
composeTestRule.onNodeWithText(string1).assertExists("No node with this text was found.")
composeTestRule.onNode(hasText(string2), useUnmergedTree = false).assertExists()
composeTestRule.onNode(hasText(string3), useUnmergedTree = false).assertExists()
...
As @Martin Zeitler pointed, to reduce bothersome, define the global string variables and assign them inside each @Test
.
class AppUITests {
@get:Rule
val composeTestRule = createComposeRule()
// Global variables
var string1 = ""
var string2 = ""
var string3 = ""
@Test
fun uiTest() {
composeTestRule.setContent {
string1 = stringResource(id = R.string.string1)
string2 = stringResource(id = R.string.string2)
string3 = stringResource(id = R.string.string3)
AppTheme {
TestComponent()
}
}
...