在测试中使用Espresso时,可能出现“androidx.test.espresso.NoMatchingRootException: Matcher 'is toast' did not match any of the following roots:”异常。这是由于Espresso无法找到所需的根视图而引起的。
通常,这个异常是由于测试代码中使用了错误的根视图引起的,或者是由于我们没有正确地缓存根视图。以下是一些可行的解决方案:
检查你的测试代码,并确认你正在使用正确的根视图。如果你的应用有多个根视图,你需要正确地引用每个根视图。如果你在测试代码中使用了错误的根视图,那么Espresso将无法找到你想要的视图。
在测试代码中,我们可以使用onView()方法来查找视图。但是,如果我们不正确地缓存根视图,你的测试代码在查找视图时可能会失败。
我们可以使用@Before注释和ActivityTestRule来缓存根视图。例如:
public class MainActivityTest { private Activity mActivity; private View mDecorView;
@Rule
public ActivityTestRule mActivityRule =
new ActivityTestRule<>(MainActivity.class);
@Before
public void setUp() throws Exception {
mActivity = mActivityRule.getActivity();
mDecorView = mActivity.getWindow().getDecorView();
}
@Test
public void testButton() throws Exception {
onView(withId(R.id.my_button)).perform(click());
}
}
在setUp()方法中,我们通过getWindow().getDecorView()方法缓存了根视图,并将其赋值给了mDecorView。这样,我们就可以在测试代码中使用正确的根视图,从而避免了Espresso查找视图时出错。