我正在使用UiAutomator跨应用程序编写一些自动化测试用例。我的目标是找到我点击的所有应用程序的当前活动。
我有一个名为MyApp的项目,包名为com。例如有一个活动,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连接到监视器。我能够在代码的这一行中获得活动实例
Activity currentActivity=instrumentation.waitForMonitorWithTimeout(monitor,3000);
现在如果我更改流主菜单-->SomeOtherApp,并使用完全合格的SomeOtherApp启动器活动连接到监视器,例如com.sometherap.MainActivity。我无法获取活动实例。currentActivity为空
有没有一种方法可以获得我通过UiAutomator启动的任何应用程序的当前活动实例?
似乎只有同一个包中的活动才能被监控,对于另一个应用程序的活动,waitForActivityWithTimeout只返回null。
如果你只获得上下文所需api的活动实例,可以像我做一样
- 在ui automator测试类的同一个包中启动活动
- 使用监视器获取该活动
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);
}
}