我正在使用UIAutomator/Espresso测试我的应用程序,我想要做以下几点:
在我的应用程序上执行某些操作/检查
打开默认浏览器并访问一个URL
返回到我的应用程序并重新检查界面
实际上,我无法完成第二步。这里是我尝试过的不同方式:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://stackoverflow.com/"));
mActivityTestRule.launchActivity(browserIntent);
InstrumentationRegistry.getTargetContext().sendBroadcast(browserIntent);
InstrumentationRegistry.getInstrumentation().startActivitySync(browserIntent);
我在Stack Overflow上搜索,但还没有找到解决方案。
@LargeTest
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BackgroundForegroundTest {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
private UiDevice mDevice;
@Before
public void before() {
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
assertThat(mDevice, notNullValue());
}
@Test
public void testOpenBrowserAndSwitchBack() throws InterruptedException {
onView(withId(R.id.text1)).check(matches(isDisplayed()));
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://stackoverflow.com/"));
mActivityTestRule.launchActivity(browserIntent);
Thread.sleep(8000);
getBackToApp("My App");
onView(withId(R.id.text1)).check(matches(isDisplayed()));
}
private void getBackToApp(String appDescription){
try {
mDevice.pressRecentApps();
UiSelector selector = new UiSelector();
UiObject recentApp = mDevice.findObject(selector.descriptionContains(appDescription));
recentApp.click();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (UiObjectNotFoundException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}