UiAutomatorTestCase getUiDevice()NullPointerException

时间:2014-09-08 07:19:37

标签: java android adt

在UiAutomatorTestCase中调用getUiDevice()时,我得到null。

public class DemoTestCase extends UiAutomatorTestCase{
    public void testDemo() {
        assertTrue(getUiDevice().pressHome());
        Bundle status = new Bundle();
        status.putString("msg", "This is a demo test and I just pressed HOME");
        status.putString("product", getUiDevice().getProductName());
        Point p = getUiDevice().getDisplaySizeDp();
        status.putInt("dp-width", p.x);
        status.putInt("dp-height", p.y);
        getAutomationSupport().sendStatus(Activity.RESULT_OK, status);
    }
}

我尝试了不同的示例并且总是变为null,但我没有获得UI设备。此测试是从应用程序的主Java类调用的。

我在运行uiautomator测试时使用了一个android VirtualBox。我使用adb push发送应用程序并使用adb shell运行uiautomator runtest my.jar -c my.main.Class

如果我不使用getUiDevice(),一切正常。

1 个答案:

答案 0 :(得分:0)

如果你从另一个类调用getUiDevice(),你必须在构造函数中声明你的变量并从原始类中调用它。

public class OriginalClass extends UiAutomatorTestCase {
    public void runTestInAnotherClass() {
        DemoTestCase demoTestCase = new DemoTestCase(getUiDevice());
        testDemo();
    }

}

public class DemoTestCase extends UiAutomatorTestCase{
    UiDevice uiDevice;

    public DemoTestCase(UiDevice device) {
        uiDevice = device;
    }

    public void testDemo() {
        assertTrue(device.pressHome());
        Bundle status = new Bundle();
        status.putString("msg", "This is a demo test and I just pressed HOME");
        status.putString("product", device.getProductName());
        Point p = device.getDisplaySizeDp();
        status.putInt("dp-width", p.x);
        status.putInt("dp-height", p.y);
        getAutomationSupport().sendStatus(Activity.RESULT_OK, status);
    }
}
相关问题