3

我正在我的应用程序中使用 UiAutomator 跨应用程序编写一些自动化测试用例。我的目标是找到我点击的所有应用程序的当前活动。

我有一个名为MyApp的项目,其中包含一个名为com.example的包,其中包含一个活动MainActivity

我尝试了以下(androidTest下我的应用程序中的所有内容)

public class ActivityTester extends InstrumentationTestCase {

private UiDevice device;

@Test
public void testAdd() throws Exception {

}

@Override
protected void setUp() throws Exception {
    super.setUp();

    Instrumentation instrumentation = getInstrumentation();

    Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor("com.example.MainActivity", null, false);


    device = UiDevice.getInstance(instrumentation);

    device.pressHome();

    device.wait(Until.hasObject(By.desc("Apps")), 3000);

    UiObject2 appsButton = device.findObject(By.desc("Apps"));
    appsButton.click();

    device.wait(Until.hasObject(By.text("MyApp")), 3000);

    UiObject2 calculatorApp = device.findObject(By.text("MyApp"));
    calculatorApp.click();

    Activity currentActivity = instrumentation.waitForMonitorWithTimeout(monitor, 3000);

}

在这里,我单击HomeMenu并启动Myapp并使用com.example.MyActivity附加到监视器,我可以在这行代码中获取活动实例

活动 currentActivity = instrumentation.waitForMonitorWithTimeout(monitor, 3000);

现在如果我改变流程。HomeMenu --> SomeOtherApp并使用 SomeOtherApp 的完全限定的launcherActivity 连接到监视器说com.someotherapp.MainActivity。我无法获取活动实例。当前活动为空

有没有办法可以获取我通过 UiAutomator 启动的任何应用程序的当前 Activity 实例?

4

1 回答 1

1

似乎只能监视同一包中的活动,因为另一个应用程序的活动 waitForActivityWithTimeout 只返回 null。

如果你只获取上下文需要的 api 的活动实例,可能会像我一样跟随

  1. 在 ui-automator-test-class 的同一个包中启动活动
  2. 使用监视器来获取该活动

    public class ExampleInstrumentedTest {

      private UiDevice mDevice;
      private Activity mActivity;

      @Before
      public void before() {
        // Initialize UiDevice instance
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

        mActivity = getActivity();

        // Start from the home screen
        mDevice.pressHome();
      }

      private Activity getActivity() {
        Activity activity = null;
        Instrumentation inst = InstrumentationRegistry.getInstrumentation();
        Context context = inst.getContext();
        Instrumentation.ActivityMonitor monitor =
                inst.addMonitor("com.wispeedio.uiautomator2hello.MainActivity", null, false);

        Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage("com.wispeedio.uiautomator2hello");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        activity = monitor.waitForActivityWithTimeout(2000);

        return activity;
      }

      private void takeScreenshot(String name) {
        File file = Utils.CreateFileToExternal(mActivity, name, "test-screenshots");
        mDevice.takeScreenshot(file);
      }
    }
于 2018-01-15T09:12:08.930 回答