Testing the UI can help us prevent the user from discovering unexpected situations, crashing the application, or getting poor performance. We strongly recommend you to write UI tests so you are sure your UI performs as expected. For this purpose, we will introduce the Espresso Framework.
First of all, we will add the dependency for it as follows:
... compile 'com.android.support.test.espresso:espresso-core:2.2.2' androidTestCompile 'com.android.support.test.espresso:espresso-
core:2.2.2' ...
Before you write and run Espresso tests, disable animations on your testing device because this will affect tests, expected timings, and behaviors. We strongly recommend you to do that! On your device, go to Settings | Developer options | and turn off the following:
- Window animation scale
- Transition animation scale
- Animator duration scale
Now you are ready to write Espresso tests. Learning the Espresso Framework can take some effort. It can be time consuming for you, but its benefit will be huge! Let's take a look at the example of one Espresso test:
@RunWith(AndroidJUnit4::class) class MainScreenTest { @Rule val mainActivityRule =
ActivityTestRule(MainActivity::class.java) @Test fun testMainActivity(){ onView((withId(R.id.toolbar))).perform(click()) onView(withText("My dialog")).check(matches(isDisplayed())) } }
We defined that we will test the MainActivity class. After the test triggers the toolbar button click, we check if the dialog is present. We do that by checking the label availability--"My dialog". Learning the entire Espresso Framework is beyond this book, but at least we gave you a hint of possibilities. Invest some time in learning it because it will definitely help you!