package mock
The mock package contains testable versions of all the standard ZIO
environment types through the MockClock, MockConsole,
MockSystem, and MockRandom modules. See the documentation on the
individual modules for more detail about using each of them.
If you are using ZIO Test and extending DefaultRunnableSpec a
MockEnvironment containing all of them will be automatically provided to
each of your tests. Otherwise, the easiest way to use the mocking
functionality in ZIO Test is by providing the MockEnvironment to your
program.
import zio.test.mock._
myProgram.provideManaged(mockEnvironmentManaged)Then all environmental effects, such as printing to the console or
generating random numbers, will be implemented by the MockEnvironment and
will be fully testable. When you do need to access the "live" environment,
for example to print debugging information to the close, just use the live
combinator along with the effect as your normally would.
If you are only interested in one of the mocking modules for your
application, you can also access them a la carte through the make method
on each module. Each mock module requires some data on initialization.
Default data is included for each as DefaultData.
import zio.test.mock._
myProgram.provideM(MockConsole.make(MockConsole.DefaultData))Finally, you can create a Mock object that implements the mock interface
directly using the makeMock method. This can be useful when you want to
access some mocking functionality without using the environment type.
import zio.test.mock._ for { mockRandom <- MockRandom.makeMock(MockRandom.DefaultData) n <- mockRandom.nextInt } yield n
This can also be useful when you are creating a more complex environment to provide the implementation for mock services that you mix in.
- Alphabetic
- By Inheritance
- mock
- AnyRef
- Any
- Hide All
- Show All
- Public
- All
Type Members
- trait Live[+R] extends AnyRef
The
Livetrait provides access to the "live" environment from within the mock environment for effects such as printing test results to the console or timing out tests where it is necessary to access the real environment.The
Livetrait provides access to the "live" environment from within the mock environment for effects such as printing test results to the console or timing out tests where it is necessary to access the real environment.The easiest way to access the "live" environment is to use the
livemethod with an effect that would otherwise access the mock environment.import zio.clock import zio.test.mock._ val realTime = live(clock.nanoTime)
The
withLivemethod can be used to apply a transformation to an effect with the live environment while ensuring that the effect itself still runs with the mock environment, for example to time out a test. Both of these methods are re-exported in themockpackage for easy availability. - trait MockClock extends Clock with Scheduler
MockClockmakes it easy to deterministically and efficiently test effects involving the passage of time.MockClockmakes it easy to deterministically and efficiently test effects involving the passage of time.Instead of waiting for actual time to pass,
sleepand methods implemented in terms of it schedule effects to take place at a given clock time. Users can adjust the clock time using theadjustandsetTimemethods, 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
MockClock:import zio.ZIO import zio.duration._ import zio.test.mock.MockClock for { fiber <- ZIO.sleep(5.minutes).timeout(1.minute).fork _ <- MockClock.adjust(1.minute) result <- fiber.join } yield result == None
Note how we forked the fiber that
sleepwas invoked on. Calls tosleepand 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 usingMockClockis 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
FiberRefand is incremented for the duration each fiber is sleeping. Child fibers inherit the fiber time of their parent so methods that rely on repeatedsleepcalls work as you would expect.For example, here is how we can test an effect that recurs with a fixed delay:
import zio.Queue import zio.duration._ import zio.test.mock.MockClock for { q <- Queue.unbounded[Unit] _ <- (q.offer(()).delay(60.minutes)).forever.fork a <- q.poll.map(_.isEmpty) _ <- MockClock.adjust(60.minutes) b <- q.take.as(true) c <- q.poll.map(_.isEmpty) _ <- MockClock.adjust(60.minutes) d <- q.take.as(true) e <- q.poll.map(_.isEmpty) } yield a && b && c && d && e
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.
- trait MockConsole extends Console
MockConsoleprovides a testable interface for programs interacting with the console by modeling input and output as reading from and writing to intput and output buffers maintained byMockConsoleand backed by aRef.MockConsoleprovides a testable interface for programs interacting with the console by modeling input and output as reading from and writing to intput and output buffers maintained byMockConsoleand backed by aRef.All calls to
putStrandputStrLnusing theMockConsolewill write the string to the output buffer and all calls togetStrLnwill take a string from the input buffer. No actual printing or reading from the console will occur.MockConsolehas several methods to access and manipulate the content of these buffers includingfeedLinesto feed strings to the input buffer that will then be returned by calls togetStrLn,outputto get the content of the output buffer from calls toputStrandputStrLn, andclearInputandclearOutputto clear the respective buffers.Together, these functions make it easy to test programs interacting with the console.
import zio.console._ import zio.test.mock._ import zio.ZIO val sayHello = for { name <- getStrLn _ <- putStrLn("Hello, " + name + "!") } yield () for { _ <- MockConsole.feedLines("John", "Jane", "Sally") _ <- ZIO.collectAll(List.fill(3)(sayHello)) result <- MockConsole.output } yield result == Vector("Hello, John!\n", "Hello, Jane!\n", "Hello, Sally!\n")
- case class MockEnvironment(blocking: Service[Any], clock: Mock, console: Mock, live: Service[Clock with Console with System with Random with Blocking], random: Mock, scheduler: Mock, sized: Service[Any], system: Mock) extends Blocking with Live[Clock with Console with System with Random with Blocking] with MockClock with MockConsole with MockRandom with MockSystem with Scheduler with Sized with Product with Serializable
- trait MockRandom extends Random
MockRandomallows for deterministically testing effects involving randomness.MockRandomallows for deterministically testing effects involving randomness.MockRandomoperates in two modes. In the first mode,MockRandomis a purely functional pseudo-random number generator. It will generate pseudo-random values just likescala.util.Randomexcept that no internal state is mutated. Instead, methods likenextIntdescribe state transitions from one random state to another that are automatically composed together through methods likeflatMap. The random seed can be set usingsetSeedandMockRandomis guaranteed to return the same sequence of values for any given seed. This is useful for deterministically generating a sequence of pseudo-random values and powers the property based testing functionality in ZIO Test.In the second mode,
MockRandommaintains an internal buffer of values that can be "fed" with methods such asfeedIntsand then when random values of that type are generated they will first be taken from the buffer. This is useful for verifying that functions produce the expected output for a given sequence of "random" inputs.import zio.random._ import zio.test.mock.MockRandom for { _ <- MockRandom.feedInts(4, 5, 2) x <- random.nextInt(6) y <- random.nextInt(6) z <- random.nextInt(6) } yield x + y + z == 11
MockRandomwill automatically take values from the buffer if a value of the appropriate type is available and otherwise generate a pseudo-random value, so there is nothing you need to do to switch between the two modes. Just generate random values as you normally would to get pseudo-random values, or feed in values of your own to get those values back. You can also use methods likeclearIntsto clear the buffer of values of a given type so you can fill the buffer with new values or go back to pseuedo-random number generation. - trait MockSystem extends System
MockSystemsupports deterministic testing of effects involving system properties.MockSystemsupports deterministic testing of effects involving system properties. Internally,MockSystemmaintains mappings of environment variables and system properties that can be set and accessed. No actual environment variables or system properties will be accessed or set as a result of these actions.import zio.system import zio.test.mock._ for { _ <- MockSystem.putProperty("java.vm.name", "VM") result <- system.property("java.vm.name") } yield result == Some("VM")
Value Members
- def live[R, E, A](zio: ZIO[R, E, A]): ZIO[Live[R], E, A]
Provides an effect with the "real" environment as opposed to the mock environment.
Provides an effect with the "real" environment as opposed to the mock environment. This is useful for performing effects such as timing out tests, accessing the real time, or printing to the real console.
- val mockEnvironmentManaged: Managed[Nothing, MockEnvironment]
A managed version of the
MockEnvironmentcontaining testable versions of all the standard ZIO environmental effects. - def withLive[R, R1, E, E1, A, B](zio: ZIO[R, E, A])(f: (IO[E, A]) => ZIO[R1, E1, B]): ZIO[R with Live[R1], E1, B]
Transforms this effect with the specified function.
Transforms this effect with the specified function. The mock environment will be provided to this effect, but the live environment will be provided to the transformation function. This can be useful for applying transformations to an effect that require access to the "real" environment while ensuring that the effect itself uses the mock environment.
withLive(test)(_.timeout(duration))
- object Live
- object MockClock extends Serializable
- object MockConsole extends Serializable
- object MockEnvironment extends Serializable
- object MockRandom extends Serializable
- object MockSystem extends Serializable