如何断言在前台运行的活动?

时间:2018-12-06 12:56:40

标签: android android-espresso android-testing android-uiautomator

我有一个DeepLinkHandlerActivity类,可以处理我的所有深层链接。为了对其进行测试,我编写了以下代码。无法弄清楚如何测试一段时间后前台的活动是否是期望的活动?知道怎么做吗?

class DeepLinkHandlerTest {

@Before
@Throws(Exception::class)
fun setUp() {
}

@After
@Throws(Exception::class)
fun tearDown() {
}

@get:Rule
val activityTestRule = ActivityTestRule<DeepLinkHandlerActivity>(DeepLinkHandlerActivity::class.java)

@Test
fun validalidUrlTest() {
    val url = "myapp://loadwebview"
    triggerDeeplink(url)

    Thread.sleep(5000)

    // what to do here? 
    // some form of assertion that correct activity is in foreground. 
}

private fun triggerDeeplink(url: String) {
    val intent = Intent("android.intent.action.VIEW", Uri.parse(url))
    activityTestRule.launchActivity(intent)
}
}

3 个答案:

答案 0 :(得分:0)

一种方法是在每个活动中都有一个静态标志,并在该活动的onPause和onResume方法上触发它。那么您可以检查该标志以查看活动是否在前台。

答案 1 :(得分:0)

android blueprint中有一种方法,但是我不确定它是否有效。

/**
 * Gets an Activity in the RESUMED stage.
 * <p>
 * This method should never be called from the Main thread. In certain situations there might
 * be more than one Activities in RESUMED stage, but only one is returned.
 * See {@link ActivityLifecycleMonitor}.
 */
public static Activity getCurrentActivity() throws IllegalStateException {
    // The array is just to wrap the Activity and be able to access it from the Runnable.
    final Activity[] resumedActivity = new Activity[1];

    getInstrumentation().runOnMainSync(new Runnable() {
        public void run() {
            Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance()
                    .getActivitiesInStage(RESUMED);
            if (resumedActivities.iterator().hasNext()) {
                resumedActivity[0] = (Activity) resumedActivities.iterator().next();
            } else {
                throw new IllegalStateException("No Activity in stage RESUMED");
            }
        }
    });
    return resumedActivity[0];
}

答案 2 :(得分:0)

最终做了这样的事情:

https://www.codexpedia.com/android/ui-test-deep-linking-using-espresso-in-android/

如果有更好的方法,请公开提出建议。