Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Class Type as Parameter and Check Type Against Another Object in Kotlin

I am attempting to write a method to wait for a type of activity to be present for my Espresso tests. I've seen examples of trying to wait for objects to appear on separate activities than where the test begins, but none have worked for me so far and I'm not keen to modify my production code with idling resources.

In my method, I'd like to get the current activity, and then check if the activity is the specific type of class that I'm wanting. I'm basically modifying some code I found here to work with Kotlin and a generic class type. Unfortunately, I don't know how to either format the argument that is being passed in (currently Class<out Activity>) or I'm improperly using it in my if statement. What is written below doesn't compile.

Any pointers on how to pass my desired activity type as a parameter to the waitForActivity method and how to check against it?

fun waitForActivity(activityType: Class<out Activity>, timeout: Int = 10): Boolean {
    val endTime = System.currentTimeMillis() + (timeout * 1000)

    do {
        val currentActivity = getActivityInstance()

        // THIS LINE IS MY ISSUE **********************************************
        if(currentActivity != null && currentActivity::class.java is activityType)
            return true
        // ********************************************************************

        SystemClock.sleep(100)
    } while (System.currentTimeMillis() < endTime)
    return false
}

private fun getActivityInstance(): Activity? {
    val activity = arrayOfNulls<Activity>(1)
    InstrumentationRegistry.getInstrumentation().runOnMainSync {
        val currentActivity: Activity?
        val resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)
        if (resumedActivities.iterator().hasNext()) {
            currentActivity = resumedActivities.iterator().next() as Activity
            activity[0] = currentActivity
        }
    }
    return activity[0]
}
like image 664
Stonz2 Avatar asked Apr 16 '18 15:04

Stonz2


1 Answers

You can replace the entire line using Class.isInstance.

if (activityType.isInstance(currentActivity)) { ... }

In Kotlin, is requires a class name (at compile time, you can't use a String either) - instead of a Class instance. Class.isInstance is used to perform the same check using a Class instance.

like image 67
apetranzilla Avatar answered Nov 10 '22 15:11

apetranzilla