If you want to read about JUnit tests then read this post. JUnit tests test the Java behaviour of your app. But to test the Android behaviour we need instrumented tests. They require a full Android environment and that is why they run on an Android Device or Emulator. One type is the unit instrumented test and another type is the automated UI test that checks the application behaviour when there are UI interactions.
We should use @RunWith(AndroidJUnit4.class) before the class declaration. Also, all the annotations from the JUnit tests are used with this type of test: @Test, @Before, @After, etc. The Assert class and its method also used. UI test needs a way to specify a view that we gonna use and a way to specify an action to perform. Espresso’s class onView method is used to specify a view and returns a ViewInteraction object. The ViewInteraction class has a method called perform() that allows us to perform one or more actions. onView needs a matcher to match the criteria. For basic matches Hamcrest matchers are used, but ViewMatcher class is used to match Android views. ActivityTestRules is used to start and destroy an activity for the test.
Create an Instrumented test file
Open an activity class file and press Ctrl + Shift + T and click Create new Test
Choose the destination directory. Choose the one that has androidTest directory and click OK
The new test class file will open
Above the class declaration you need to insert the @RunWith annotation that passes the parameter AndroidJUnit4.class
Create a test
Now, let’s create a test. First, we need to specify the activity we gonna use, using ActivityTestRule. You need to add to Build.gradfile the dependency
Create a test method
Create a ViewInteraction for the view with id R.id.text.view . I use the withId method to match the view.Then type on the text view with the perform() method and using the method typeText(“”)
The above we can combine it in one line
To perform a click action use the click() method
If you want to click to listView or spinner, you need to use onData instead of onView. It returns a DataInteraction object which provides the perform method so we can interact with the match.
You need to specify the object you need to find, and then find it with the allOf matcher
For spinner view it is required an additional step. You need to click on the view to open the list of the objects. It should be before the onData
If you want to press the back button then use:
You can verify a test by using the check method. You can add it at a separate line or add it at the end.