Functional tests Android Espresso with fragments

I have three actions in my application

  • Login Activity
  • Primary activity
  • Detailed description

I want to use espresso to check the sequence of events: press the login button to enter the system that will open the main action, and then click the list item in the main action that will open the detailed activity, and then click another button in the details. I started by creating this simple test to get a link to a list:

public class LoginActivityTest extends ActivityInstrumentationTestCase2<LoginActivity> { public LoginActivityTest() { super(LoginActivity.class); } @Override public void setUp() throws Exception { super.setUp(); getActivity(); } public void testSequence() throws Exception { // Login onView(withId(R.id.button_log_in)).perform(click()); // Check if MainActivity is loaded onView(withId(R.id.container)).check(matches(isDisplayed())); // Check if Fragment is loaded onView(withId(R.id.list)).check(matches(isDisplayed())); } } 

In the mainActivity onCreate() method, I load the following snippet:

 getFragmentManager().beginTransaction() .add(R.id.container, mListFragment) .commit(); 

The ListFragment flag has a list ( R.id.list ), but still the test failed with a NoMatchingViewException :

 android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with id: com.tests.android.development:id/list 

What am I doing wrong?

+6
source share
2 answers

Note from the documentation for onView :

Note: The view must be part of the view hierarchy. This may not be the case if it is displayed as part of the adapter (for example, ListView). If so, use Espresso.onData to load the view first.

To use onData to load the view, you need to check for instances of any of your adapter in the ListView. In other words, if your list uses a cursor adapter, you can try the following:

 onData(allOf(is(instanceOf(Cursor.class)))).check(matches(isDisplayed())); 

It is important to note that the above will be executed only if your list contains at least one element. It is recommended that you have one test where the element exists and one test where there is no element.

For more information on how to check existing data, see here .

For more information on how to check data that does not exist in the adapter, see here .

+1
source

In the current version (Espresso 2.2.2), this exception is always added with the View Hierarchy: clause, which lists all viewable views. Go through this and see if you can find your list.

Alternatively: check android-sdk\tools\uiautomatorviewer.bat (or .sh), which takes a snapshot from the current screen and hierarchy. Put a breakpoint in the list matching line and check if it has a list. If you find the list, a synchronization problem may occur in the test. Perhaps this did not wait enough, look more about IdlingResource s.

0
source

Source: https://habr.com/ru/post/982327/


All Articles