使用Espresso测试Android PreferenceFragment
作者:互联网
我正在尝试在“设置”中为PreferenceFragments片段编写测试.
但是,我一直收到这个错误:
android.support.test.espresso.NoMatchingViewException:层次结构中找不到匹配的视图:可从类中分配:class android.widget.AdapterView
测试代码如下:
@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;
}
}
settings_activity布局如下所示:
<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" />
首选项屏幕布局如下:
<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>
我无法在线找到有关如何测试PreferenceFragments的任何示例或信息.大多数与测试活动有关的信息.
解决方法:
PreferenceMatchers似乎只适用于Android框架中的首选项类,但不适用于支持首选项库(com.android.support:preference-v14).由于后者在内部使用RecylerView,我可以通过使用espresso-contrib中的RecyclerViewActions来获取首选项:
onView(withId(R.id.list))
.perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_manage_categories_title)),
click()));
标签:android,testing,android-espresso,espresso 来源: https://codeday.me/bug/20190622/1264584.html