Last active
March 16, 2017 14:04
-
-
Save exallium/0aa998e05e81b686fe79976b271d61cc to your computer and use it in GitHub Desktop.
unit testing a debounce
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
@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