Android上的单元测试期间的区域设置

时间:2013-05-26 14:26:38

标签: android unit-testing globalization

我有一些我想测试的代码。我想检查String是否由我在资源中的各种字符串正确组成。这里的挑战是处理我的资源中的多个翻译。我知道在测试桌面应用程序时,语言环境可能是个问题,建议您创建与语言环境无关的测试。

我发现您可以以编程方式设置区域设置,但不建议这样做(请参阅Change language programmatically in Android)。虽然这个问题的目的是在正常运行应用程序时在运行时更改语言环境,但我想知道是否有更好的解决方案来解决我的问题。

1 个答案:

答案 0 :(得分:49)

如果仅用于测试,则可以通过编程方式更改语言环境而不会出现任何问题。它将更改您的应用程序的配置,您将能够使用新的区域设置测试您的代码。它具有与用户更改它相同的效果。如果要自动化测试,可以编写一个脚本,使用adb shell作为described here更改区域设置,然后启动测试。

以下是测试英语,德语和西班牙语语言环境中“取消”字词的翻译的示例:

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

}

以下是Eclipse中的执行结果:

enter image description here

Android O更新。

在Android O中运行时,应使用Locale.setDefault(Category.DISPLAY, locale)方法(有关详情,请参阅behaviour changes)。

相关问题