I’m having drop testing a function that uses a wit...
# test
j
I’m having drop testing a function that uses a withTimeoutOrNull(). Is there a recommended way of testing such code?
c
What do you want to test exactly?
j
I have some logic (
flow
collection) thats wrapped in a
withTimeoutOrNull(…) {}
and I would like to test proper timeout logic but using delays to emit values into my flow above don’t seem to work. When testing, the timeout would expire even when the delay was below the delays used.
Using
advanceTimeBy(...)
seemed to help a bit but my bigger issue is I’m not sure if that’s the proper solution or if I’m just changing my test slightly therefore making it no longer valid by don’t realize.
c
Do you have a way to force the operation to be slow? (so it triggers the timeout)
j
I used a long delay inside of
flow {}
before I emitted an item.
c
It's hard to answer with so little info, but I would do something like:
Copy code
runTest {
    val yourThingAsync = async {
        // the thing you want to test, ensure there is an infinite delay within the withTimeoutOrNull {}
    }

    delay(5.minutes) // or however long the timeout should be
    check(yourThingAsync.isComplete)
    val yourThing = yourThingAsync.await()
    check(yourThing.…)
}
(or something like that, I don't have a test project to check the exact function names)
c
make the delay configurable, and use 0 as timeout in the test. tests should never delay or depend on time
c
@christophsturm What if you want to test the delay itself? In some situations, delaying or timing out for a given length of time is part of the business rules.
c
if your component depends on time then you need to inject a clock
c
withTimeout
is based on a
TimeSource
, not a
Clock
, but sure, that's still only half of the answer. How would you write it?