在espresso测试案例中device.getCurrentPackagename返回null

时间:2019-11-23 17:33:24

标签: android-espresso

这是我的测试方法

@Test
    public void testLeadChangeStageToUnqualifiedReason() throws InterruptedException {
        List<Map<String, Object>> leadData = LeadData.simpleLead();
        lead.createLead(leadData);
        Thread.sleep(3000);
        LeadPage.waitForLandingPage();
        lead.changeStage("Unqualified","Not interested");
        onView(withText("Lead stage changed")).inRoot(new ToastMatcher())
                .check(matches(isDisplayed()));
                    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
            device.wait(Until.findObject(By.res(device.getCurrentPackageName(), "lead_stage_txt")), 7000);
            stage = device.findObject(By.res(device.getCurrentPackageName(), "lead_stage_txt")).getText();
        CommonHelpers.tapLandingBackButton();
        CommonHelpers.tapHomeScreenButton();
        Assert.assertEquals("Stage name differed", stage,"Unqualified");
    }

因此,在验证了Toast消息之后,我试图使用UIObject获取元素的文本,不幸的是,我得到device.getCurrentPackageName()作为Null会导致异常

我还尝试了InstrumentationRegistry.getInstrumentation().getUiAutomation().getRootInActiveWindow();,它也返回Null

任何人都可以在这个问题上提供帮助

将根节点设置为空

以上内容也无效 当我打电话给device.findObject时 我将rootNode设置为空

AccessibilityNodeInfo getRootNode() {
        final int maxRetry = 6;
        long waitInterval = 250;
        AccessibilityNodeInfo rootNode = null;
        for (int x = 0; x < maxRetry; x++) {
            rootNode = mUiAutomatorBridge.getRootInActiveWindow();
            if (rootNode != null) {
                return rootNode;
            }
            if (x < maxRetry - 1) {
                Log.e(LOG_TAG, "Got null root node from accessibility - Retrying...");
                SystemClock.sleep(waitInterval);
                waitInterval *= 2;
            }
        }
        return rootNode;
    }

1 个答案:

答案 0 :(得分:0)

您可以尝试使用InstrumentationRegistry.getTargetContext().getPackageName()吗?

您也可以将其包含在const变量中,该变量可以在测试之间重复使用。

private static final String TARGET_PACKAGE_NAME =
            InstrumentationRegistry.getTargetContext().getPackageName();

另外,为了访问应用程序中的字符串,您可以使用相同的上下文,而不必手动输入 例如,

sampleString=InstrumentationRegistry.getTargetContext().getString(R.string.sample)
mDevice.findObject(By.desc(sampleString)).click();