我想测试用户更改语言时字符串是否正确更新。我使用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()
}
}
问题是espresso测试onView(withText(expected)).check(matches(isDisplayed()))
断言是假的,所以我想知道在运行测试之前设置默认语言环境的正确方法是什么?
答案 0 :(得分:1)
根据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。
答案 1 :(得分:1)
Kotlin版本,基于@Adib Faramarzi的帖子
private fun setLocale(language: String, country: String) {
val locale = Locale(language, country)
// here we update locale for date formatters
Locale.setDefault(locale)
// here we update locale for app resources
val context: Context = getApplicationContext()
val res: Resources = context.resources
val config: Configuration = res.configuration
config.setLocales(LocaleList(locale))
res.updateConfiguration(config, res.displayMetrics)
}
答案 2 :(得分:0)
根据我的经验,在运行时设置语言环境根本不可靠。这个人在这里有更多关于这个话题的话题:https://proandroiddev.com/change-language-programmatically-at-runtime-on-android-5e6bc15c758
您应该尝试使用Firebase测试实验室或类似服务,并在不同设备上运行测试(设置了不同的区域设置)