我在用 Expresso 测试我的代码时遇到了问题。我写了这段代码:
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/preferences_xml">
<PreferenceCategory
android:title="@string/application_settings"
android:id="@+id/application_settings_preferences">
<CheckBoxPreference
android:key="@string/key_processing_private_data_preference"
android:title="@string/title_processing_private_data_preference"
android:summary="@string/summary_processing_private_data_preference"
android:defaultValue="true"
android:dependency="@string/key_recording_audio_preference"
android:id="@+id/private_data_check_box_preference"/>
</PreferenceCategory>
<PreferenceCategory
android:title="@string/device_settings"
android:id="@+id/device_settings_preferences">
<CheckBoxPreference
android:key="@string/key_recording_audio_preference"
android:title="@string/title_recording_audio_preference"
android:summary="@string/summary_recording_audio_preference"
android:defaultValue="true"
android:id="@+id/recording_audio_check_box_preference"/>
</PreferenceCategory>
</PreferenceScreen>
我的测试规则:
@Rule
public ActivityTestRule<SettingsActivity> mActivityRule = new ActivityTestRule<>(
SettingsActivity.class);
我尝试测试第一个复选框:
onData(anything())
.inAdapterView(allOf(
isDescendantOfA(withId(R.id.preferences_xml)),
withId(R.id.application_settings_preferences)))
.atPosition(1)
.check(matches(isDisplayed()));
测试总是失败并出现 NoMatchingViewException:层次结构中没有找到匹配的视图:
我也尝试:
String workingInBackgroundSummary = mActivityRule.getActivity().getBaseContext().getString(R.string.summary_working_in_background_preference);
onData(withSummaryText(workingInBackgroundSummary)).check(matches(isDisplayed()));
测试总是因 NullPointerException 而失败:
onView(withId(R.id.working_in_background_check_box_preference)).check(matches(isDisplayed()));
也因 NoMatchingViewException 而失败。
有人会展示一个带有正确测试用例的例子吗?