Android Espresso Testing Framework

As mobile developers, we spend most of our time creating new screens or changing screens that already exist and we need to know that the code works. That is why in our development process we must use tools to verify that our application continues to work as expected and that our development meets the quality of the desired product according to the user story. And in this article, we will talk about Espresso Testing.

Testing in Android majorly involves two types:

1.Unit Tests

2.Instrumentation Tests

Espresso comes under the second type. It is used to do automated UI testing by writing short and concise Android UI tests.

Getting Started With Espresso Tests

Add the following dependencies in the build.gradle file:

Add the following in the defaultConfig block :

Espresso has basically three components:

1.ViewMatchers -Finds the view
2.ViewActions – Performs an action on the view
3.ViewAssertions – Validates a assertioin

Inside the onView we look for the id of the View.

It can be done using methods like:

Inside perform we pass the action to be done on the View. Example:

Inside check we assert the states mainly using methods:

Writing Espresso Tests

Espresso tests are written inside src | androidTest folder files.
By default, ExampleInstrumentedTest.java is created with a default test.

Let’s write one test:

@Rule annotation is used to launch the MainActivity.
Inside loginClickedSuccess we wrote a successful login test case.

Now let’s write two more tests in which we will test whether the Toast is shown correctly or not.

Add the following methods inside the above class:

The last line is used to check whether Toast is displayed with the correct string or not.

To run the espresso test. Right click on the ExampleInstrumentationTest.java and press run to start the automated test on the emulator/physical device.
Espresso Test Recording

You can record Espresso tests manually as well:

1.Click on Run.

2.Agter that Click Record Espresso Test.

It will automatically create a new file with the espresso tests containing the manual clicks and actions you did in the device.

Espresso resources

https://developer.android.com/training/testing/espresso

https://developer.android.com/training/testing/ui-testing/espresso-testing

https://developer.android.com/studio/test/espresso-test-recorder

Comments