Android测试:等待视图层次结构的根获得窗口焦点

fjaof16o  于 2023-03-21  发布在  Android
关注(0)|答案(8)|浏览(184)

在Android Ui测试中,我想点击对话框中的一个微调项,但它弹出了以下错误:

va.lang.RuntimeException: Waited for the root of the view hierarchy to have window focus and not be requesting layout for over 10 seconds. If you specified a non default root matcher, it may be picking a root that never takes focus. Otherwise, something is seriously wrong. Selected Root:
Root{application-window-token=android.view.ViewRootImpl$W@2dac97c7, window-token=android.view.ViewRootImpl$W@2dac97c7, has-window-focus=false, layout-params-type=1, layout-params-string=WM.LayoutParams{(0,0)(fillxfill) sim=#10 ty=1 fl=#81810100 pfl=0x8 wanim=0x1030461 surfaceInsets=Rect(0, 0 - 0, 0) mwfl=0x0}, decor-view-string=MultiPhoneDecorView{id=-1, visibility=VISIBLE, width=1600, height=2560, has-focus=true, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}
. All Roots:
Root{application-window-token=android.view.ViewRootImpl$W@3c913e1, window-token=android.view.ViewRootImpl$W@21b23506, has-window-focus=true, layout-params-type=1002, layout-params-string=WM.LayoutParams{(310,600)(722x480) gr=#10000033 sim=#1 ty=1002 fl=#1860200 fmt=-3 wanim=0x10302db surfaceInsets=Rect(0, 0 - 0, 0) mwfl=0x0}, decor-view-string=PopupViewContainer{id=-1, visibility=VISIBLE, width=722, height=480, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}
Root{application-window-token=android.view.ViewRootImpl$W@3c913e1, window-token=android.view.ViewRootImpl$W@3c913e1, has-window-focus=false, layout-params-type=2, layout-params-string=WM.LayoutParams{(0,0)(wrapxwrap) gr=#11 sim=#20 ty=2 fl=#1800002 pfl=0x8 fmt=-3 wanim=0x1030462 surfaceInsets=Rect(0, 0 - 0, 0) mwfl=0x10}, decor-view-string=DecorView{id=-1, visibility=VISIBLE, width=1136, height=1058, has-focus=true, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}
Root{application-window-token=android.view.ViewRootImpl$W@2dac97c7, window-token=android.view.ViewRootImpl$W@2dac97c7, has-window-focus=false, layout-params-type=1, layout-params-string=WM.LayoutParams{(0,0)(fillxfill) sim=#10 ty=1 fl=#81810100 pfl=0x8 wanim=0x1030461 surfaceInsets=Rect(0, 0 - 0, 0) mwfl=0x0}, decor-view-string=MultiPhoneDecorView{id=-1, visibility=VISIBLE, width=1600, height=2560, has-focus=true, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}
at android.support.test.espresso.base.RootViewPicker.get(RootViewPicker.java:99)
at android.support.test.espresso.ViewInteractionModule.provideRootView(ViewInteractionModule.java:69)
at android.support.test.espresso.ViewInteractionModule_ProvideRootViewFactory.get(ViewInteractionModule_ProvideRootViewFactory.java:23)
at android.support.test.espresso.ViewInteractionModule_ProvideRootViewFactory.get(ViewInteractionModule_ProvideRootViewFactory.java:9)
at android.support.test.espresso.base.ViewFinderImpl.getView(ViewFinderImpl.java:68)
at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:120)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6117)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

我试过了

onData(allOf(is(instanceOf(String.class)),containsString("A4"))).inRoot(isPlatformPopup()).perform(click());

以及

onView(withText(containsString("A4"))).inRoot(isFocusable()).check(matches(isDisplayed()));

以及

onView(withText(containsString("A4"))).inRoot(withDecorView(not(getActivity().getWindow().getDecorView()))).check(matches(isDisplayed()));

但是都不管用...有没有人能告诉我怎么弄到雷拉Vant根?

syqv5f0l

syqv5f0l1#

当系统对话框显示时(如"Power Off""Unfortunately, Launcher has stopped"(后台应用程序崩溃)),您尝试在该对话框可见时运行Espresso单元测试时,可能会发生此错误。

您可以通过在运行测试之前关闭系统对话框来在代码中解决此问题:

// Use the 'testing' Context
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

// Alternative: Use the Activity for the Context
MyActivity activityUnderTest = activityTestRule.getActivity();
activityUnderTest.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

或者使用adb在命令行上发送广播:

adb shell am broadcast -a android.intent.action.CLOSE_SYSTEM_DIALOGS

出现错误的另一个原因是后台应用程序冻结(ANR)或运行缓慢,系统对话框显示"Launcher isn't responding. Do you want to close it? [Wait] [OK]"

如果您在此对话框可见时尝试运行Espresso测试,则所有测试都将失败并显示“Waited for the root...”(等待根...)错误。无法通过编程方式关闭此对话框。Espresso无法单击这些按钮,原因如下所述:Dismiss Alert Dialog in Android Espresso Test。但是,一种方法是使用UI Automator在测试开始之前按下对话框中的“等待”按钮:

应用程序/构建版本.gradle

dependencies {
    ...
    androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
}

活动UI测试.kt

companion object {
    @JvmStatic
    @BeforeClass
    fun dismissANRSystemDialog() {
        val device = UiDevice.getInstance(getInstrumentation())
        // If running the device in English Locale
        var waitButton = device.findObject(UiSelector().textContains("wait"))
        if (waitButton.exists()) {
            waitButton.click()
        }
        // If running the device in Japanese Locale
        waitButton = device.findObject(UiSelector().textContains("待機"))
        if (waitButton.exists()) {
            waitButton.click()
        }
    }
}

ActivityUiTest.java

@BeforeClass
public static void dismissANRSystemDialog() throws UiObjectNotFoundException {
    UiDevice device = UiDevice.getInstance(getInstrumentation());
    // If the device is running in English Locale
    UiObject waitButton = device.findObject(new UiSelector().textContains("wait"));
    if (waitButton.exists()) {
        waitButton.click();
    }
    // If the device is running in Japanese Locale
    waitButton = device.findObject(new UiSelector().textContains("待機"));
    if (waitButton.exists()) {
        waitButton.click();
    }
}

或者,您可以在命令行中使用adb来发送screen tapskey strokes以消除它。

# On a 320x480 screen, click at screen location [x=233,y=293] to tap an "OK" dialog button.
# Just in case there is a "Launcher isn't responding" system dialog.
adb shell input tap 233 293

# Send keystroke Arrow Right
sleep 3; adb shell input keyevent 22
# Send keystroke Arrow Right again
sleep 3; adb shell input keyevent 22
# Send keystroke Enter to press a button on the dialog
sleep 3; adb shell input keyevent 66

更多信息:

guykilcj

guykilcj2#

当我在DialogFragment中使用Spinner时,我也遇到了同样的错误。这是唯一对我有效的代码:

onView(withText(containsString("A4"))).inRoot(isPlatformPopup()).check(matches(isDisplayed()));
c2e8gylq

c2e8gylq3#

当弹出对话框包含微调项(下拉列表)时,我遇到了类似的问题,我的点击无法在任何微调项上执行,并得到了相同的错误。我找到了一个解决方案,通过使用与RootMatchers的onData()方法:

onData(anything()).inRoot(RootMatchers.isPlatformPopup()).atPosition(1).perform(click());

注意,***atPosition()***中的索引值是微调器列表中项目的索引值。

bkkx9g8r

bkkx9g8r4#

以防万一,如果它发生在任何人的特拉维斯构建(与完全相同的日志)。请检查这一点。
有完全相同的问题,并解决了创建avd与较低的目标版本(19)
我试过但没成功的:

  • 向UI测试添加unlockScreen()@Before方法。
  • 添加/删除adb shell input keyevent 82 &
  • 删除不同的emulator命令选项-no-skin-no-audio-no-window。现在我有-no-window在那里,这是好的。

最后,从

echo no | android create avd --force -n test -t android-24 --abi armeabi-v7a

echo no | android create avd --force -n test -t android-19 --abi armeabi-v7a

完美地解决了这个问题。

tzdcorbm

tzdcorbm5#

对我来说,在测试我的定制AlertDialog时,使用.inRoot(isDialog())方法代替.inRoot(isPlatformPopup())是有效的。

onView(withText(containsString("A4"))).inRoot(isDialog()).check(matches(isDisplayed()));
pkmbmrz7

pkmbmrz76#

我在CI中的模拟器上运行Espresso测试时定期遇到这个问题。因为如果单个测试失败,检查也会失败,所以https://stackoverflow.com/a/54203607/4520965中的答案不足以满足我的用例。该答案处理在后续测试类中消除ANR对话框。但是ANR最初出现的测试类仍然失败。为了解决这个问题,我在所有Espresso测试继承的基础ui测试类中添加了以下内容:

//Running count of the number of Android Not Responding dialogues to prevent endless dismissal.
    private var AnrCount = 0 
    //`RootViewWithoutFocusException` class is private, need to match the message (instead of using type matching).
    private val rootViewWithoutFocusExceptionMsg = java.lang.String.format(
            Locale.ROOT,
            "Waited for the root of the view hierarchy to have "
                    + "window focus and not request layout for 10 seconds. If you specified a non "
                    + "default root matcher, it may be picking a root that never takes focus. "
                    + "Root:")

    @Before
    fun setUpHandler() {
        Espresso.setFailureHandler { error, viewMatcher ->
            
            if (error.message!!.contains(rootViewWithoutFocusExceptionMsg) && AnrCount < 3) {
                AnrCount++
                handleAnrDialogue()
            } else { // chain all failures down to the default espresso handler
                DefaultFailureHandler(context).handle(error, viewMatcher)
            }
        }
    }

    private fun handleAnrDialogue() {
        val device = UiDevice.getInstance(getInstrumentation())
        // If running the device in English Locale
        val waitButton = device.findObject(UiSelector().textContains("wait"))
        if (waitButton.exists()) waitButton.click()
    }
2admgd59

2admgd597#

只需更新travis.yml中的构建工具:

  • 在此文件.travis.yml中:你应该有这个before_install: - echo yes | android update sdk --all --filter build-tools-26.0.1 --no-ui --force
  • .travis.yml中也是如此:
script: echo no | android create avd --force -n test -t android-22
--abi armeabi-v7a emulator -avd test -no-audio -no-window & 
android-wait-for-emulator 
adb shell settings put global window_animation_scale 0 &
adb shell settings put global transition_animation_scale 0 &
adb shell settings put global animator_duration_scale 0 &
adb shell input keyevent 82 &
q1qsirdb

q1qsirdb8#

也许问题是最新的,但与新的Android版本.
AndroidX测试:1.3.0
特浓咖啡:3.3.0
安卓操作系统:安卓11(API 30)
参见https://github.com/android/android-test/issues/751

相关问题