Android 更改测试区域设置

Rgf*_*Iff 4 android kotlin

我想测试当用户更改语言时字符串是否正确更新。我用来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()
    }

}
Run Code Online (Sandbox Code Playgroud)

问题是浓缩咖啡测试onView(withText(expected)).check(matches(isDisplayed()))断言错误,所以我想知道在运行测试之前设置默认区域设置的正确方法是什么?

Adi*_*rzi 6

根据这个答案,您可以以编程方式更改区域设置:

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

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