トラッキング コード

3/01/2015

How to check Toast window, on android test-kit Espresso

If we read the following public document, we can check other window.
Using inRoot to target non-default windows

1
2
3
onView(withText("South China Sea"))
  .inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
  .perform(click());

But, I think this is not cool.

We can create a custom matcher.
Toast window has the WindowManager.LayoutParams.TYPE_TOAST.

The followinf code is sample.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Matcher that is Toast window.
 */
public static Matcher<Root> isToast() {
    return new 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) {
                    // windowToken == appToken means this window isn't contained by any other windows.
                    // if it was a window for an activity, it would have TYPE_BASE_APPLICATION.
                    return true;
                }
            }
            return false;
        }
    };
}