Skip to content

Instantly share code, notes, and snippets.

@josefadamcik
Last active February 20, 2020 08:15
Show Gist options
  • Save josefadamcik/bdde55c10a30ac86eaf2b8b95d09d1c8 to your computer and use it in GitHub Desktop.
Save josefadamcik/bdde55c10a30ac86eaf2b8b95d09d1c8 to your computer and use it in GitHub Desktop.
ViewTestRule - for testing of isolated views using instrumented tests on android.
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