Android Espresso:如何检查Toast消息是否未显示?

前端之家收集整理的这篇文章主要介绍了Android Espresso:如何检查Toast消息是否未显示?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我现在正在进行功能测试,其中一个我必须测试没有显示吐司信息.考虑到这是我用来检查是否显示toast消息的代码(此代码有效):
onView(withText(R.string.my_toast_message))
        .inRoot(withDecorView(not(getActivity().getWindow().getDecorView())))
        .check(matches(isDisplayed()));

下面你可以找到我用来检查没有显示吐司信息的代码(它们都不起作用):

方法一:

onView(withText(R.string.error_invalid_login))
        .inRoot(withDecorView(not(getActivity().getWindow().getDecorView())))
        .check(matches(not(isDisplayed())));

方法二:

onView(withText(R.string.error_invalid_login))
        .inRoot(withDecorView(not(getActivity().getWindow().getDecorView())))
        .check(doesNotExist());

任何关于如何检查未显示吐司信息的想法都会非常感激:)

解决方法

在espresso中测试toast消息的最佳方法是使用自定义匹配器:
public class ToastMatcher extends TypeSafeMatcher<Root> {
    @Override public void describeTo(Description description) {
        description.appendText("is toast");
    }

    @Override public boolean matchesSafely(Root root) {
        int type = root.getWindowLayoutParams().get().type;
        if ((type == WindowManager.LayoutParams.TYPE_TOAST)) {
            IBinder windowToken = root.getDecorView().getWindowToken();
            IBinder appToken = root.getDecorView().getApplicationWindowToken();
            if (windowToken == appToken) {
                //means this window isn't contained by any other windows. 
            }
        }
        return false;
    }
}

您可以在测试用例中使用它:

>测试是否显示Toast消息

onView(withText(R.string.message)).inRoot(new ToastMatcher())
.check(matches(isDisplayed()));

>测试是否未显示Toast消息

onView(withText(R.string.message)).inRoot(new ToastMatcher())
.check(matches(not(isDisplayed())));

>测试ID Toast包含特定的文本消息

onView(withText(R.string.message)).inRoot(new ToastMatcher())
.check(matches(withText("Invalid Name"));

我从我的博客中复制了这个答案 –
http://qaautomated.blogspot.in/2016/01/how-to-test-toast-message-using-espresso.html

原文链接:https://www.f2er.com/android/308612.html

猜你在找的Android相关文章