trait
TestClock extends Clock with Scheduler
Concrete Value Members
-
final
def
!=(arg0: Any): Boolean
-
final
def
##(): Int
-
final
def
==(arg0: Any): Boolean
-
final
def
asInstanceOf[T0]: T0
-
def
clone(): AnyRef
-
-
-
def
finalize(): Unit
-
final
def
getClass(): Class[_]
-
def
hashCode(): Int
-
final
def
isInstanceOf[T0]: Boolean
-
-
final
def
notify(): Unit
-
final
def
notifyAll(): Unit
-
final
def
synchronized[T0](arg0: ⇒ T0): T0
-
def
toString(): String
-
final
def
wait(): Unit
-
final
def
wait(arg0: Long, arg1: Int): Unit
-
final
def
wait(arg0: Long): Unit
TestClock
makes it easy to deterministically and efficiently test effects involving the passage of time.Instead of waiting for actual time to pass,
sleep
and methods implemented in terms of it schedule effects to take place at a given clock time. Users can adjust the clock time using theadjust
andsetTime
methods, and all effects scheduled to take place on or before that time will automically be run.For example, here is how we can test ZIO.timeout using
TestClock:
Note how we forked the fiber that
sleep
was invoked on. Calls tosleep
and methods derived from it will semantically block until the time is set to on or after the time they are scheduled to run. If we didn't fork the fiber on which we called sleep we would never get to set the the time on the line below. Thus, a useful pattern when usingTestClock
is to fork the effect being tested, then adjust the clock to the desired time, and finally verify that the expected effects have been performed.Sleep and related combinators schedule events to occur at a specified duration in the future relative to the current fiber time (e.g. 10 seconds from the current fiber time). The fiber time is backed by a
FiberRef
and is incremented for the duration each fiber is sleeping. Child fibers inherit the fiber time of their parent so methods that rely on repeatedsleep
calls work as you would expect.For example, here is how we can test an effect that recurs with a fixed delay:
Here we verify that no effect is performed before the recurrence period, that an effect is performed after the recurrence period, and that the effect is performed exactly once. The key thing to note here is that after each recurrence the next recurrence is scheduled to occur at the appropriate time in the future, so when we adjust the clock by 60 minutes exactly one value is placed in the queue, and when we adjust the clock by another 60 minutes exactly one more value is placed in the queue.