Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Testing your Android App's UI with Espresso

July 13, 2017
Abishek V Ashok
Related topics:
Developer toolsJava
Related products:
Red Hat build of Node.js

    Android is one of the most used mobile operating systems in the market with an estimated market share of approximately 84.82%. Millions of apps loom in the Android OS, for various tasks and it's a shame that only a small percentage of the apps have a well-developed user interface (UI), which is flexible and adaptable to various mobile sizes. For an average user, they want their apps to look good and do well. However, if you are an app developer there will be a monstrous problem for you, Android is open source and it comes in all sorts of mobile phones with all sorts of screen sizes. Android developers have taught of this problem and have introduced a new automated testing framework to test the UI of your app called Espresso.

    Espresso, as I stated above is an automated testing framework introduced by Android to test your app's user interface and ensure that it's all fine across all those devices with weird sizes. So, I would show you how to get Espresso up and running testing your apps activities step by step. We will actually have 2 blog posts, one to get things started and the other one as Part two to support multiple screen sizes on a CI platform to reduce the length of the blog. So let's start by setting Espresso up first.

    Setting up Espresso

    Setting up Espresso is simple, just like the JUnit test runner (which is already added) we add Espresso to our app's `build.gradle` file under the dependencies section:

    dependencies {
        // Other dependencies ...
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'
        androidTestImplementation 'com.android.support.test:runner:0.5'
    }

    Note: Most of Android's and Google's website specifies to use 'androidTestCompile' but I've used 'androidTestImplementation' that's because Google revealed in it's I/O 2017, that the 'compile' group ['compile', 'androidTestCompile' etc.] will be depreciated in the near future and will be replaced by the 'implementation' group.

    Ok, since we got Espresso included let's dive into how to write some tests for Espresso and remember I won't be designing any UI here. I would just be explaining, how we will write Espresso tests.

    Writing Espresso Tests

    So, you go to the Espresso tests directory [/app/src/java/com/example/android/testing/espresso] in your app and you create a new Java class.

    Then you can specify which all UI's the test should run with '@RunWith()' and specify the JUnit test to run along. Then you specify the class name like you do with all other Java files, then you specify rules with '@Rule' and things to do before tests run with '@Before'. Lastly, you specify the tests with '@Test'.

    You need to initialize Activity test rule with the activity to test and specify the corresponding Java file.

    You will initialize the variables inside functions denoted by '@Before'. The function name can be anything.

    Then, we will push out our tests inside a function with the '@Test' tag.

    We can now begin testing. We can test almost every UI element provided it has a valid unique 'id' set. We do so, by using the onView function provided in espresso, we provide an integer generated with another function called 'withId()' to whom we provide the 'id' as a parameter like 'R.id.blah'. Then we specify what action we need to perform. Espresso provides actions as subfunctions like '.perform(click())', '.perform(typeText(String text))'. We can also check whether these tests are fine with '.check()' subfunction.

    Here's a sample test provided from the Android developer's website:

    package com.example.android.testing.espresso.BasicSample;
    
    import org.junit.Before;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    import android.support.test.rule.ActivityTestRule;
    import android.support.test.runner.AndroidJUnit4;
    ...
    
    @RunWith(AndroidJUnit4.class)
    @LargeTest
    public class ChangeTextBehaviorTest {
    
        private String mStringToBetyped;
    
        @Rule
        public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
                MainActivity.class);
    
        @Before
        public void initValidString() {
            // Specify a valid string.
            mStringToBetyped = "Espresso";
        }
    
        @Test
        public void changeText_sameActivity() {
            // Type text and then press the button.
            onView(withId(R.id.editTextUserInput))
                    .perform(typeText(mStringToBetyped), closeSoftKeyboard());
            onView(withId(R.id.changeTextBt)).perform(click());
    
            // Check that the text was changed.
            onView(withId(R.id.textToBeChanged))
                    .check(matches(withText(mStringToBetyped)));
        }
    }

    Then you sit back and run your tests with a virtual machine or an Android phone. We will dive into how we would move forward to test all those weird screen sizes in the next tutorial.

    Wrapping up, for now, hope you all had a great time...
    Happy coding :)


    Red Hat Mobile Application Platform is available for download, and you can read more at Red Hat Mobile Application Platform.

    Last updated: October 31, 2023

    Recent Posts

    • LogAn: Large-scale log analysis with small language models

    • stalld’s BPF Backend: Breaking Free from debugfs

    • Running AI inference on Rebellions ATOM NPU with Red Hat AI

    • How we built integration testing for fast-moving AI backend

    • Testing infrastructure red teaming with abliterated models

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.