gpt4 book ai didi

Android 更改语言环境以进行测试

转载 作者:行者123 更新时间:2023-11-30 00:03:47 25 4
gpt4 key购买 nike

我想测试当用户更改语言时字符串是否正确更新。我正在使用 Espresso 来测试字符串是否与正确的语言环境匹配,我目前正在这样更改它:

private fun changeLocale(language: String, country: String) {
val locale = Locale(language, country)
Locale.setDefault(locale)
val configuration = Configuration()
configuration.locale = locale
context.activity.baseContext.createConfigurationContext(configuration)


getInstrumentation().runOnMainSync {
context.activity.recreate()
}

}

问题是浓缩咖啡测试 onView(withText(expected)).check(matches(isDisplayed())) 断言为 false 所以我想知道设置默认值的正确方法是什么运行测试之前的语言环境?

最佳答案

根据 this回答,您可以通过编程方式更改语言环境:

public class ResourcesTestCase extends AndroidTestCase {

private void setLocale(String language, String country) {
Locale locale = new Locale(language, country);
// here we update locale for date formatters
Locale.setDefault(locale);
// here we update locale for app resources
Resources res = getContext().getResources();
Configuration config = res.getConfiguration();
config.locale = locale;
res.updateConfiguration(config, res.getDisplayMetrics());
}

public void testEnglishLocale() {
setLocale("en", "EN");
String cancelString = getContext().getString(R.string.cancel);
assertEquals("Cancel", cancelString);
}

public void testGermanLocale() {
setLocale("de", "DE");
String cancelString = getContext().getString(R.string.cancel);
assertEquals("Abbrechen", cancelString);
}

public void testSpanishLocale() {
setLocale("es", "ES");
String cancelString = getContext().getString(R.string.cancel);
assertEquals("Cancelar", cancelString);
}

}

您可以轻松将该代码转换为 Kotlin。

关于Android 更改语言环境以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49419554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com