Android-在JUnit / Espresso测试中更改语言环境以使用Rules生成应用程序屏幕截图

时间:2018-12-26 15:11:44

标签: java android junit android-espresso

我正在尝试使用JUnit和Espresso生成应​​用程序屏幕截图。问题在于,在截取屏幕截图之前,我还需要更改设备(仿真器)的语言环境,而这部分不起作用(尽管没有错误)。屏幕截图是使用在仿真器设备中设置的语言环境拍摄的,而不是我在测试中设置的语言环境拍摄的。

我创建了一个LocaleRule来设置语言环境。

public class LocaleRule implements TestRule {
    private final Locale locale;
    private Locale mDeviceLocale;

    public LocaleRule(Locale locale) {
        this.locale = locale;
    }


    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                   mDeviceLocale = Locale.getDefault();
                   setLocale(locale);
                   base.evaluate();
                } finally {
                    if (mDeviceLocale != null) {
                        setLocale(mDeviceLocale);
                    }
                }
            }
        };
    }


    private void setLocale(Locale locale) {
        Resources resources = InstrumentationRegistry.getTargetContext().getResources();
        Locale.setDefault(locale);
        Configuration config = new Configuration(resources.getConfiguration());
        config.setLocale(locale);
        resources.updateConfiguration(config, resources.getDisplayMetrics());
    }
}

这是测试班。

    @RunWith(AndroidJUnit4.class)
public class CountrySelectionActivityScreenshot {

    private final LocaleRule mLocaleRule = new LocaleRule(english());
    private final ActivityTestRule mActivityTestRule = new ActivityTestRule<>(CountrySelectionActivity.class);
    private final ScreenshotWatcher mScreenshotWatcher = new ScreenshotWatcher();
    private final GrantPermissionRule mGrantPermissionRule = GrantPermissionRule.grant(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE);

    @Rule
    public final RuleChain mRuleChain = RuleChain.outerRule(mLocaleRule)
            .around(mScreenshotWatcher)
            .around(mGrantPermissionRule)
            .around(mActivityTestRule);

    @Test
    public void countrySelectionActivityPortrait() {
    }
}

0 个答案:

没有答案