Instrumentation Testing Of ListView

      1 Comment on Instrumentation Testing Of ListView

In this post we will learn how to write simple instrumentation test. We will be testing an app which has a listView. We will test that list has items in it and on clicking on an item it goes to item’s detail page. For this post I have created a demo application with a list view, the code can be found here. It has following activities.

1. ItemListActivity

This activity is responsible for showing a list view with some static entries in it.

 

2. ItemDetailActivity

This activity is responsible for showing the detail of an item on click. The details will include only the title of the Item.

Gradle Config

androidTestCompile ‘com.android.support.test:rules:0.3’
Instrumentation tests will be written with the help of this dependency. It has an internal dependency to test:runner:0.3 library which provides some class which are essential for our tests.

Enough of application knowledge, lets jump into our tests.

Scenario 1 – I want to verify the number of items displayed in the list view.

ActivityTestRule – This class is used to test a single Activity. It will launch the activity before starting your test.

In the test, we are getting our list view from the activity and asserting that it has 4 items.

Scenario 2 – I want to verify the name of the item in the list.

In this test, we are again getting the list view then getting an item from the list and asserting its name.

Scenario 3 – Click an item in the list and go to its details page.

In the above test there are quite a few things to learn. Lets go through them one by one.
runOnMainSync  In order to click on an item in the list, we have to perform our click action in the main thread of our application otherwise test will throw the following error.

Instrumentation.ActivityMonitor – Clicking on an item will take us to the ItemDetailActivity, which is a bit time consuming operation. So this class helps us to monitor the launch of ItemDetailActivity.
instrumentation.waitForMonitorWithTimeout(monitor, 5000) – This will wait for 5 seconds until the activity is launched, if activity is not launched it will fail. And this is a blocking code, so if you put this code before launching the activity which is before clicking one of the items then it will keep on waiting for it and will fail after the time out. So make sure that you put it in the right place.
Also this method returns back the target activity which makes our life easier to test the components on that activity.

At last in the test we assert the text on the ItemDetailActivity.

Thats All Folks!!

One thought on “Instrumentation Testing Of ListView

Leave a Reply

Your email address will not be published. Required fields are marked *