Generating Android app screenshot with Screengrab


Screengrab is a part of Fastlane. It can help us to generate screenshot with different languages.

Before you use Screengrab, you need to write UI test with Espresso. Because Screengrab capture screenshot through Espresso.

Create simple application are text view and button with two locales English and Thai.

screenshot-2016-08-09-21-09-42

 

When to clicking on the button, it will show snack bar on the current language.

Screenshot 2016-08-09 21.09.56

Installation

sudo gem install screengrab

Setup
Create Screengrabfile by running.

    screengrab init

Modify package name and locales list, we need to capture in Screengrabfile

    app_package_name 'com.bananacoding.fastlanescreengrab'

    locales ['en-US', 'th-TH']

Add dependency in build.gradle

    dependencies {
        ...
        androidTestCompile 'tools.fastlane:screengrab:0.4.0'
    }

Add user permission in AndroidManifest.xml

   <!-- Allows unlocking your device and activating its screen so UI tests can succeed -->
   <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
   <uses-permission android:name="android.permission.WAKE_LOCK"/>

   <!-- Allows for storing and retrieving screenshots -->
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

   <!-- Allows changing locales -->
   <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />

Add LocalTestRule in your test class to handle automatic switching of locales.

    @ClassRule
    public static final LocaleTestRule localeTestRule = new LocaleTestRule();

Then use Screengrab.screenshot() in the test to capture screenshot.

    @RunWith(AndroidJUnit4.class)
    public class MainActivityTest {

        @ClassRule
        public static final LocaleTestRule localeTestRule = new LocaleTestRule();

        @Rule
        public ActivityTestRule activityTestRule = new ActivityTestRule<>(MainActivity.class);

        @Test
        public void clickButton_shouldShowLanguage() {
            Screengrab.screenshot("before_click");

            onView(withId(R.id.btn_click_me)).perform(click());

            Screengrab.screenshot("after_click");

            onView(withText(R.string.current_language)).check(matches(isDisplayed()));
        }
    }

Generate screenshot
First, we need the debug and test apk file. Create by run following command.

    ./gradlew assembleDebug assembleAndroidTest

Then, capture screenshot by run screengrab to generate screenshot with all locales.

Screenshot 2016-08-09 22.45.25

Here the result.

Screenshot 2016-08-09 22.45.20

Source Code: GitHub


Leave a Reply

Your email address will not be published.