Skip to content

Instantly share code, notes, and snippets.

@westonal
Last active December 16, 2017 17:58
Show Gist options
  • Save westonal/5f45a71b7f4bfe3910dd5759e0206ad1 to your computer and use it in GitHub Desktop.
Save westonal/5f45a71b7f4bfe3910dd5759e0206ad1 to your computer and use it in GitHub Desktop.
Kotlin JUnit rules
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
private class Rule(private val before: () -> Unit, private val after: () -> Unit) : TestRule {
override fun apply(base: Statement, description: Description?) =
object : Statement() {
override fun evaluate() {
try {
before()
base.evaluate()
} finally {
after()
}
}
}
}
interface After {
infix fun after(doThis: () -> Unit): TestRule
}
private class Before(private val doThat: () -> Unit) : After {
override infix fun after(doThis: () -> Unit) = Rule(doThat, doThis)
}
fun before(doThis: () -> Unit): After = Before(doThis)

Usage

@get:Rule
val myRule =
    before {
       X()
    } after {
       Y()
    }

Rx rules

fun ioSchedulerTrampoline() = Schedulers.trampoline().useForIo()

fun Scheduler.useForIo() =
        before {
            RxJavaPlugins.setIoSchedulerHandler { this }
        } after {
            RxJavaPlugins.reset()
        }
@get:Rule
val ioSchedulerTrampoline = ioSchedulerTrampoline()
val testScheduler = TestScheduler()

@get:Rule
val ioScheduler = testScheduler.useForIo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment