Skip to content

Instantly share code, notes, and snippets.

@Lamartio
Last active April 30, 2018 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lamartio/92ce33d3a487cc16c5c30c1c6683fb1a to your computer and use it in GitHub Desktop.
Save Lamartio/92ce33d3a487cc16c5c30c1c6683fb1a to your computer and use it in GitHub Desktop.
The logic from https://github.com/novoda/espresso-support bundled in a single .kt file
import android.app.Activity
import android.app.Instrumentation
import android.content.Context
import android.support.annotation.LayoutRes
import android.support.test.InstrumentationRegistry
import android.support.test.rule.ActivityTestRule
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* Don't forget to add this Activity to your manifest.
*/
class ViewTestRuleActivity : Activity()
class ViewTestRule<T : View> constructor(
private val instrumentation: Instrumentation,
private val viewCreator: (Context, ViewGroup) -> T
) : ActivityTestRule<ViewTestRuleActivity>(ViewTestRuleActivity::class.java) {
lateinit var view: T
private set
constructor(@LayoutRes resource: Int) : this(
InstrumentationRegistry.getInstrumentation(),
{ context, parent ->
LayoutInflater
.from(context)
.inflate(resource, parent, false)
.let { it as T }
}
)
constructor(viewCreator: (Context, ViewGroup) -> T) : this(
InstrumentationRegistry.getInstrumentation(),
viewCreator
)
override fun afterActivityLaunched() {
super.afterActivityLaunched()
instrumentation.runOnMainSync {
val root = activity
.findViewById<View>(android.R.id.content)
.let { it as ViewGroup }
view = viewCreator(activity, root)
activity.setContentView(view, view.layoutParams)
}
}
fun runOnMainSynchronously(runner: (view: T) -> Unit) {
instrumentation.runOnMainSync { runner(view) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment