10

I am trying to write tests for the PreferenceFragments fragment in Settings.

However, I've been getting this error: android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: is assignable from class: class android.widget.AdapterView

The code for the Test is the following:

@RunWith(AndroidJUnit4.class)
@SmallTest
public class SettingsFragmentTest {

    @Rule
    public ActivityTestRule<SettingsActivity> mActivityRule = new ActivityTestRule<>(
            SettingsActivity.class);

    @Test
    public void preferredLocationShouldBeVisibleOnDisplay(){
        mActivityRule.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                SettingsFragment settingsFragment = startSettingsFragment();
            }
        });

        // This check passes correctly
        onView(withId(R.id.weather_settings_fragment))
                .check(matches(isCompletelyDisplayed()));

        // This check gives me the NoMatchingViewException
        onData(allOf(is(instanceOf(Preference.class)),
                withKey("location")))
                .check(matches(isCompletelyDisplayed()));
    }

    private SettingsFragment startSettingsFragment(){
        SettingsActivity activity = mActivityRule.getActivity();
        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        SettingsFragment settingsFragment = new SettingsFragment();

        transaction.replace(R.id.weather_settings_fragment, settingsFragment, "settingsFragment");
        transaction.commit();

        return settingsFragment;
    }
}

The settings_activity layout looks as follows:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:name="com.example.android.sunshine.SettingsFragment"
          android:id="@+id/weather_settings_fragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

And the Preferences Screen layout is the following:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">

    <EditTextPreference
        android:defaultValue="@string/pref_location_default"
        android:inputType="text"
        android:key="@string/pref_location_key"
        android:singleLine="true"
        android:title="@string/pref_location_label" />

    <ListPreference
        android:defaultValue="@string/pref_units_metric"
        android:entries="@array/pref_units_options"
        android:entryValues="@array/pref_units_values"
        android:key="@string/pref_units_key"
    android:title="@string/pref_units_label" />

<CheckBoxPreference
    android:defaultValue="@bool/show_notifications_by_default"
    android:key="@string/pref_enable_notifications_key"
    android:summaryOff="@string/pref_enable_notifications_false"
    android:summaryOn="@string/pref_enable_notifications_true"
    android:title="@string/pref_enable_notifications_label" />

</PreferenceScreen>

I haven't been able to find any examples or information online on how to test PreferenceFragments. Most of the information related to testing Activities.

Marco Poloe
  • 269
  • 5
  • 13

7 Answers7

14

PreferenceMatchers seems to work only with the preference classes from the Android framework, but not with support preference library (com.android.support:preference-v14). Since the latter uses a RecylerView internally, I was able to get hold of the preference items by using RecyclerViewActions from espresso-contrib:

onView(withId(R.id.list))
       .perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_manage_categories_title)),
            click()));
mtotschnig
  • 1,238
  • 10
  • 30
  • 4
    I confirm the PreferenceMatchers neither works for Android X library. The RecyclerViewAction does work, I just had to replace R.id.list by R.id.recycler_view (in this case the UI Automator Viewer may be helpful). – Miloš Černilovský Dec 17 '18 at 11:02
  • 2
    and to be more precise: `androidx.preference.R.id.recycler_view` – Pawel Hofman Oct 02 '19 at 11:55
12

For PreferenceFragment:

PreferenceFragment uses a ListView internally, so you can use onData() with allOf() and withTitle():

onData(allOf(is(
        instanceOf(Preference.class)),
        withTitle(R.string.my_pref_string)))
        .perform(click());

Or use onData() with allOf() and withKey():

onData(allOf(is(instanceOf(Preference.class)), withKey("myPrefKey")))
        .onChildView(withText(R.string.my_pref_string))
        .perform(click());

Or use onData() with anything(), but this can be unreliable and cause timeouts:

// atPosition() is required - Not sure why
onData(anything())
        .atPosition(3)
        .onChildView(withText(R.string.my_pref_string))
        .perform(click());

Asserting or checking for a preference item is done in a similar way:

onData(allOf(is(
        instanceOf(Preference.class)),
        withTitle(R.string.my_pref_string)))
        .check(matches(isDisplayed()));

For PreferenceFragmentCompat:

PreferenceFragmentCompat uses a RecyclerView internally, so you must use the espresso-contrib library, as mentioned in the answer by mtotschnig on 3 Septemebr 2018. If you're using the androidx.preference:preference:1.x.x library with unit tests written in Kotlin, it can be tricky to know what to use. You can start with something like this:

onView(withId(androidx.preference.R.id.recycler_view))
    .perform(actionOnItem<RecyclerView.ViewHolder>(
        hasDescendant(withText(R.string.my_pref_title)), click()))

Note: To quickly add the imports for these methods, put the blinking cursor on the unresolved method, then do Android Studio ➔ HelpFind Action ➔ search for "show context action" or "show intention action" ➔ click on the result option ➔ A popup window will appear ➔ click on "Import static method ...". You can also assign a keyboard shortcut to "Show Context Actions". More info here. Another way is to enable "Add unambiguous imports on the fly" in the Settings.

Mr-IDE
  • 7,051
  • 1
  • 53
  • 59
1

After navigating to your settings activity, you can use Espresso withText() with the preference android:title String

@Rule
public ActivityTestRule<SettingsActivity> mActivityRule = new ActivityTestRule<>(
        SettingsActivity.class);

onView(withText(mActivityRule.getActivity().getResources().getString(R.string.my_pref_title))
    .perform(click());

Side note: if it is a ListPreference, then when clicking on it as mentioned above, then you can test selecting an item from the list the same way, but use the list entry text in withText() as no titles here.

onView(withText(mActivityRule.getActivity().getResources().getString(R.string.list_entry_sring))
    .perform(click());
Zain
  • 37,492
  • 7
  • 60
  • 84
0

I normally test Fragments through their activity with Espresso. Just test the UI exposed by your Fragment as if it were in the Activity that you're starting with the ActivityTestRule. If the Fragment isn't present on initial launch of the Activity, navigate in your test the same way a user would in order to start the Fragment transaction. If you find yourself needing to test business logic that requires you to stand up Fragments in some sort of test harness, that's usually a good indicator that it should be pulled out into a separate class that can be (ideally) unit tested devoid of any Android dependencies.

jdonmoyer
  • 1,245
  • 1
  • 18
  • 28
0

You can always try Record Espresso test https://developer.android.com/studio/test/espresso-test-recorder.html

Here is the tips on how to work with lists https://developer.android.com/training/testing/espresso/lists.html

This is PreferenceMatcher that expose API like this:

    onData(PreferenceMatchers.withKey(mContext.getString(R.string.key_settings)))
         .perform(click());
Roger Alien
  • 3,040
  • 1
  • 36
  • 46
  • 1
    Hi, Does it work from your end? I already tried using `PreferenceMatchers`, but I wasn't able to run it. I always encountered `android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: is assignable from class: class android.widget.AdapterView` – jjz Jun 26 '18 at 06:00
  • Thanks for the reply! So, you're using a layout instead of the `res/xml/preferences.xml`? – jjz Jun 26 '18 at 20:54
0

About PreferenceFragmentCompat, in addition to @Mr-IDE answer, checking for a preference item with scrollTo<RecyclerView.ViewHolder>

onView(withId(androidx.preference.R.id.recycler_view))
    .perform(
        scrollTo<RecyclerView.ViewHolder>(
            hasDescendant(withText(R.string.my_pref_title))
        )
    )
fireb86
  • 1,723
  • 21
  • 35
-1
@Test
    public void clickListPreference() throws Exception{

        // Check if it is displayed
        Context appContext = InstrumentationRegistry.getTargetContext();

        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_units_key))))
          .check(matches(isDisplayed()));

        // Check if click is working
        onData(allOf(
           is(instanceOf(Preference.class)),
           withKey(appContext.getResources().getString(R.string.pref_units_key))))           
          .onChildView(withText(appContext.getResources()
              .getString(R.string.pref_units_label))).perform(click());
 }

Hope this will help you..

Anjan Debnath
  • 120
  • 1
  • 8