Skip to content

Instantly share code, notes, and snippets.

@exallium
Last active March 16, 2017 14:04
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 exallium/0aa998e05e81b686fe79976b271d61cc to your computer and use it in GitHub Desktop.
Save exallium/0aa998e05e81b686fe79976b271d61cc to your computer and use it in GitHub Desktop.
unit testing a debounce
@Test
fun debounce_test() {
// TestScheduler lets us control time ;)
val testScheduler = TestScheduler()
// This basically represents a button.
val testClicks = PublishSubject<Long>()
// This'll let us verify our interactions
val testSubscriber = TestSubscriber<Long>()
// Debounce utilizes the computation scheduler by default, so we tell Rx to inject
// our TestScheduler instead. This lets us get around having to manually specify some sort
// of Injectable scheduler in the code, but requires this janky code.
RxJavaPlugins.getInstance().reset()
RxJavaPlugins.getInstance().registerSchedulersHook(object : RxJavaSchedulersHook() {
override fun getComputationScheduler(): Scheduler {
return testScheduler
}
})
// We want to only accept a click every 100ms
testClicks.debounce(100, TimeUnit.MILLISECONDS).subscribe(testSubscriber)
// 3 clicks in quick succession
testClicks.onNext(1)
testClicks.onNext(2)
testClicks.onNext(3)
// At the start of time, we have no clicks
testScheduler.triggerActions()
testSubscriber.assertValueCount(0)
// After 100 ms, we should have accepted one click
testScheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS)
testScheduler.triggerActions()
testSubscriber.assertValueCount(1)
testSubscriber.assertValues(3)
// Emit a few more clicks
testClicks.onNext(4)
testClicks.onNext(5)
testClicks.onNext(6)
// After 200 ms, we should have accepted two clicks
testScheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS)
testScheduler.triggerActions()
testSubscriber.assertValueCount(2)
testSubscriber.assertValues(3, 6)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment