Last active
February 20, 2020 08:15
-
-
Save josefadamcik/bdde55c10a30ac86eaf2b8b95d09d1c8 to your computer and use it in GitHub Desktop.
ViewTestRule - for testing of isolated views using instrumented tests on android.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ch.olmero.jo.test | |
import android.content.Context | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.test.platform.app.InstrumentationRegistry | |
import androidx.test.rule.ActivityTestRule | |
import ch.olmero.jo.EmptyTestActivity | |
/** EmptyTestActivity must be available in the build you are testing. It's just an empty activity. */ | |
class ViewTestRule<T : View>( | |
private val createView: (context: Context) -> T | |
) : ActivityTestRule<EmptyTestActivity>(EmptyTestActivity::class.java) { | |
private val instrumentation = InstrumentationRegistry.getInstrumentation() | |
/** | |
* When interacting with the view, you may need to use InstrumentationRegistry.getInstrumentation().runOnMainSync(..) | |
*/ | |
var view: T? = null | |
private set | |
override fun afterActivityLaunched() { | |
super.afterActivityLaunched() | |
instrumentation.runOnMainSync { | |
val context = activity ?: throw IllegalStateException("no activity") | |
view = createView(context) | |
context.setContentView(view, | |
ViewGroup.LayoutParams( | |
ViewGroup.LayoutParams.MATCH_PARENT, | |
ViewGroup.LayoutParams.MATCH_PARENT | |
) | |
) | |
} | |
instrumentation.waitForIdleSync() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment