App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide How to test Toast Message using Espresso?

How to test Toast Message using Espresso?

By Gaurav Prabhakar, Community Contributor -

Table of Contents

Android Toast is a small message that is displayed on the screen, similar to a tool tip or other similar popup notification. A Toast is displayed on top of the main content of an activity, and only remains visible for a short time period.

It simply provides feedback about an operation in a small popup. It fills the amount of space required for that message and the current activity remains visible and interactive.

Toast Message in the App Welcome to see youToast Message in the App “Welcome to see you!”

Toast messages are always a challenge for automation, not just because of their ephemeral nature but from the perspective of the Android Accessibility layer, toast messages are not visible. If you try to get the XML source from an Appium Inspector or UI Automator Tool session while a toast is present on screen, you won’t find any toast message text anywhere in the page source. Espresso provides the ability to match text against on-screen toasts.

How to Toast Message in Espresso

Before you can start testing toast message in Espresso, first you need to create a decorView variable and assign it before tests. The DecorView is the view that actually holds the window’s background drawable.

Run Espresso Tests on Real Devices

Here’s how you can create decorView:

private View decorView;
    @Before
    public void setUp() {
        activityRule.getScenario().onActivity(new ActivityScenario.ActivityAction<YourActivity>() {
            @Override
            public void perform(YourActivity activity) {
                decorView = activity.getWindow().getDecorView();
            }
        });
    }

Below is the Test case with assertion that would test Toast Message.

onView(withText("R.id.ToastText"))
                .inRoot(withDecorView(Matchers.not(decorView)))// Here you use decorView
                .check(matches(isDisplayed()));

Test case with assertion that would test Toast Message

Combining decorView with the Test case with assertion written to test Toast Message. 

private View decorView;

@Before
    public void setUp() {
        activityRule.getScenario().onActivity(new ActivityScenario.ActivityAction<GardenActivity>() {
            @Override
            public void perform(GardenActivity activity) {
                decorView = activity.getWindow().getDecorView();
            }
        });
    }
    //Test if the Toast Message is Displayed
    @Test
    public void testValidToast() {

        // Given that no Plants are added to the user's garden
        // When the "Add Plant" button is clicked(Yellow Button)
        onView(withId(R.id.add_plant)).perform(click());
        //Verify Toast is Displayed After clicking the Plant List Fragment
        onView(withText("Welcome For The Visit"))
                .inRoot(withDecorView(Matchers.not(decorView)))// Here we use decorView
                .check(matches(isDisplayed()));
    }
    //Test if the Toast Message is not Displayed
    @Test
    public void testToastNotDisplayed() {
        // Given that no Plants are added to the user's garden
        // When the "Add Plant" button is clicked(Yellow Button)
        onView(withId(R.id.add_plant)).perform(click());
        //Verify Toast is Displayed After clicking the Plant List Fragment
        onView(withText("Your Toast"))
                .inRoot(withDecorView(Matchers.not(decorView)))// Here we use decorView
                .check(matches(not(isDisplayed())));
    }

For official documentation of BrowserStack, visit Espresso test on BrowserStack App Automate.

Run Toast Message Test in Espresso

Create a test configuration In Android Studio:

  • Open Run menu >> Edit Configurations
  • Add a new Android Tests configuration
  • Choose a module
  • Add a specific instrumentation runner:
    android.support.test.runner.AndroidJUnitRunner
  • Add your class name

Configuration Setup

Once the configuration is setup connect your device or select the emulator and directly run the configuration.

Executing Toast Message Test in Espresso with BrowserStack

For more accurate results, it is recommended to test on real devices, taking real user conditions into account. 

Run Espresso Tests on Real Devices

With BrowserStack’s real device cloud you can run Espresso Toast Message on real devices by following the steps below:

Step 1 To Run your test cases on BrowserStack you need two apk files.

First one is your main app Apk and another is your androidTest Apk.

To generate both the apk run below command

  • To create a .apk file for the app run the following command in the terminal:
./gradlew assembleDebug
  • To create a .apk file for the test classes in the terminal run the following command:
./gradlew assembleAndroidTest

Find both .apk files under your project folder: <project-folder>\build\outputs\apk. In the apk folder you will find two files:

  • app-debug.apk
  • app-debug-androidTest.apk

These are the files that you will upload to the cloud when you create your Execution Plan.

Step 2 Get your access key from the BrowserStack using the below command 

curl -u "<username>:<access-key>" -X POST 
"https://api-cloud.browserstack.com/app-automate/upload" -F 
"file=@/path/to/app/file/Application-debug.apk"

Output

Please note the App URL (bs://<hashed appid>) returned in the response of this call:

{"app_url":"bs://<hashed appid>"}

Step 3 Upload the app by running below command on your terminal

curl -u "<username>:<access-key>" -X POST 
"https://api-cloud.browserstack.com/app-automate/espresso/test-suite" -F 
"file=@/path/to/test/file/Application-debug-test.apk"

Output

Please note the Test Suite URL (bs://<hashed testID>) returned in the response of this call:

{"test_url":"bs://<hashed testID>"}

The Test ID returned in the response will be used to execute your test.

Note: Go through the BrowserStack Docs for detailed information on Espresso

Execute Toast Message Espresso Test

To execute the test in Espresso, run the following command:

curl -u "<username>:<access-key>" \

-X POST "https://api-cloud.browserstack.com/app-automate/espresso/v2/build" \
-d '{"class": ["Test-Class-Name"], "devices": ["Samsung Galaxy S8-7.0"], "app": "bs://<hashed appid from Step 1>", "testSuite": "bs://<hashed testID from Step 2>"}' \
-H "Content-Type: application/json"
//Test-Class-Name for the above github project com.google.samples.apps.sunflower.ToastTest

The test results are available on the command-line interface, as well as the App Automate dashboard. You have now run your first Espresso test on BrowserStack App Automate.

 

Tags
Automated UI Testing Automation Testing Expresso Mobile App Testing Mobile Testing

Featured Articles

Appium vs Espresso: Key Differences

Getting Started with Espresso – Android UI Automation

Debunking Myths about Agile Testing