how to test timer schedule inside kotlin ? ``` ...
# getting-started
c
how to test timer schedule inside kotlin ?
Copy code
runBlocking {
            val pm = PeerManager(app)
            pm.start()
            val timer = Timer()
            timer.schedule(object : TimerTask() {
                override fun run() {
                    pm.stop()
                }
            }, PEER_LOOP_DELAY*5)
        }
This code seems not working
m
What's not working? What's the goal of
runBlocking
and why are you using it in the snippet. The
runBlocking
won't wait for the timer to finish since
schedule
is not a blocking call.
c
I move the code out side the runBlocking, it still can not be test ed
m
Again what is not working? Are you trying to unit test and the test is returning before the timer goes off?
c
yes
I need it stopped after
pm.stop
is executed.
m
You can use
runBlocking
and delay, or a CountdownLatch waiting for the timer to go off. In general I would rework
PeerManager
to use a virtual timer that allows you to advance its time by a given amount for testing. If it is using coroutines internally, I would look at the test dispatchers and
runTest
.
c
any simple code example?
m
If peer manager is using coroutines, modify it to be able to take a scope from the test. Then
Copy code
fun test() = runTest {
   val pm = PeerManager(app, backgroundScope)
   pm.start()
   delay(PEER_LOOP_DELAY * 5)
   pm.stop()
   // asserts
}
👍 1
If PeerManager is not using coroutines, then you need to figure out how it is delaying (assuming that is your code) and hide that behind an interface, that you can inject a no delay option or a controlled delay.
c
ok