Write Your First UI Test in Android Using Espresso

Richa Sharma
4 min readApr 10, 2022

The main agenda of UI testing is to test the aspects of any software that a user will come into contact with.UI testcases will verify that they are functioning according to requirements in terms of functionality and performance.

source : Google
  • We will understand UI testing basics in three part WHY, WHAT and HOW?

Testing Pyramid

source : Google
  • Testing pyramid is a way of thinking about different kinds of automated tests should be used to create a balanced way.
  • UI Tests- UI Testing is at the top of the pyramid, does end-to-end tests. Their objective is to imitate the end user’s behavior on an application.
  • Integration Tests- Integration tests is to verify if a set of units behave correctly, on a smaller scale than end-to-end tests.
  • Unit Tests- At the pyramid’s base, we have unit tests, in which we verify the workings of our application’s smallest unit of testable code.It tests the smallest piece of code that can be logically isolated in a system. For more basic understanding on unit test cases please go through link.

Why we need UI testing in Android?

  • Yes it is important to test UI of application to verify the functions, behaviors, correctness, and usefulness of an Android application.
  • Test execution is much faster as compared to manual testing. It will reduce small design and development bugs.

What is Espresso?

source : Google
  • Espresso is a testing framework that helps developers write automation test cases for user interface UI testing.
  • Espresso is targeted at developers, who believe that automated testing is an integral part of the development lifecycle. While it can be used for black-box testing,

What are Espresso API Component?

The main components of Espresso include the following:

  • EspressoEntry point to interactions with views (via onView() and onData()). Also exposes APIs that are not necessarily tied to any view, such as pressBack().
  • ViewMatchers — allows users to find views in the current view hierarchy.
  • ViewActions — allows to perform actions on the views.
  • ViewAssertions — allows to assert state of a view.

For more understanding of flow you can go through the Espresso Cheat Sheet

source : developer.android.com

How to start writing Espresso UI Testcases?

  • So before starting writing espresso testcases we should know some basic Annotations.
  • @Rule: This annotation means that this is a JUnit4 test rule. JUnit4 test rules are run before and after every test method.
  • @RunWith: JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit
  • @Before: indicates that the method this annotation is attached to must be executed before each test method in the class.
  • @Test: indicates that the method this annotation is attached to should run as a test case.
  • @After: indicates that the method this annotation is attached to should run after each test method.

So let’s begin….

Espresso Setup Instructions

  • In app’s build.gradle file add following dependencies
androidTestImplementation('androidx.test.espresso:espresso-core:3.4.0')
androidTestImplementation('androidx.test:runner:1.4.0')
androidTestImplementation('androidx.test:rules:1.4.0')
  • Set the Instrumentation Runner
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
  • buil.gradle example
android {
compileSdkVersion(28)

defaultConfig {
applicationId = "com.my.awesome.app"
minSdkVersion(15)
targetSdkVersion(28)
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
}

dependencies {
androidTestImplementation('androidx.test:runner:1.4.0')
androidTestImplementation('androidx.test.espresso:espresso-core:3.4.0')
}
  • Example of basic UI Testcase
@RunWith(AndroidJUnit4::class)
@LargeTest
class HelloWorldEspressoTest {

@get:Rule
val activityRule = ActivityScenarioRule(MainActivity::class.java)

@Test fun listGoesOverTheFold() {
onView(withText("Hello world!")).check(matches(isDisplayed()))
}
}
  • In above example we are testing one activity which has one text on UI “Hello world!”.
  • Here we have use ActivityScenarioRule.

What is ActivityScenarioRule?

  • ActivityScenarioRule launches a given activity before the test starts and closes after the test. You can access to scenario interface via getScenario() method. You may finish your activity manually in your test, it will not cause any problems and this rule does nothing after the test in such cases.
  • Here you need to pass the Activity which UI you want to test.

How to run Espresso UI Testcases?

  • Open the desired app module folder and navigate to the test you want to run.
  • Right-click on the test and click Run ‘testName”

or you can run with Command line:

$ ./gradlew connectedAndroidTest

How to test RecyclerView with Espresso?

  • We can test list of item on UI using Espresso.
onView(withId(R.id.recycler_view))
.check(matches(atPosition(0, withText("Hello World"))));
  • here we can test text at particular position.
  • if you want to check the text in which we perform click is matching to expected we can write
onView(withRecyclerView(R.id.recycler_view).atPosition(1)).perform(click());                                                                   onView(withId(R.id.txtname)).check(matches(isDisplayed()));

Advantages of Espresso :

  • UI automation suitable for writing black box tests.
  • Easy to setup.
  • Simplified testing by letting QAs refer to previous builds/test results and proceed further.
  • Improves performance as efficient test scripts deliver fast and accurate results.

Yes..that’s all :)

source: Google

Happy Reading :)

--

--