我对使用Espresso选择Spinners中的商品有疑问。或者更确切地说:选择有效,但之后视图断言失败,因为微调器仍处于打开状态。
让我们说我有一个非常简单的活动,其中包含一个微调器和一个显示选择的textview,如下所示:
现在,我写了一个Espresso测试,选择了“狗”和“狗”。并验证textview是否相应更新:
@Test
public void selectDogs() throws Exception {
onData(allOf(is(instanceOf(String.class)), is("dogs")))
.inAdapterView(withId(R.id.spinner))
.perform(click());
onView(withId(R.id.selected)).check(matches(withText("dogs")));
}
该测试失败,因为onData()...perform(click());
没有关闭微调器,它只是让它打开。通过调试验证:
例外是:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with id: org.flinc.app:id/selected
If the target view is not part of the view hierarchy, you may need to use Espresso.onData to load it from one of the following AdapterViews:android.widget.ListPopupWindow$DropDownListView{226cb88 VFED.VC.. .F...... 0,0-231,432}
我可以(通过在微调器选择后添加pressBack()
来修复我的测试,但对我而言,这不是正确的解决方案。它也会在模拟器上出现问题,但它似乎在我的设备上正常运行。
如何在微调器中正确选择然后关闭它?
非常感谢你的帮助!
以下是参考活动代码:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_spinner);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
final TextView selected = (TextView) findViewById(R.id.selected);
final List<String> items = Arrays.asList("cats", "dogs", "unicorns");
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selected.setText(items.get(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
selected.setText("");
}
});
}
答案 0 :(得分:0)
您必须先点击微调器,然后使用以下代码:
@Test
public void selectDogs() throws Exception {
onView(withId(R.id.spinner)).perform(click());
onData(allOf(is(instanceOf(String.class)), is("dogs")))
.perform(click());
onView(withId(R.id.selected)).check(matches(withText("dogs")));
}