title: Android - Change locale in JUnit/Espresso test to generate app screenshots using Rules
body: <p>I'm trying to use JUnit and Espresso to generate app screenshots. The problem is that I also need to change the device (emulator) locale before taking the screenshot, and this part is not working (no errors though). The screenshot is taken with the locale set in the emulator device, not with the one I set on the test.</p>
  
  <p>I created a LocaleRule to set the locale.</p>
  
  <pre><code>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());
      }
  }
  </code></pre>
  
  <p>And this is the test class.</p>
  
  <pre><code>    @RunWith(AndroidJUnit4.class)
  public class CountrySelectionActivityScreenshot {
  
      private final LocaleRule mLocaleRule = new LocaleRule(english());
      private final ActivityTestRule mActivityTestRule = new ActivityTestRule&lt;&gt;(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() {
      }
  }
  </code></pre>