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



我有一个类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)
}
}

有一个来自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];
}
一种方法是在每个活动中都有一个静态标志,并在活动的onPause和onResume方法上触发它。然后您可以检查该标志以查看活动是否在前台。

最终做了这样的事情:

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

如果有更好的方法,欢迎提出建议。

最新更新