Test a ZIO Application End to End
Welcome! This tutorial is for developers who have written a first ZIO Test spec, as shown in Writing Tests, and now want to test a whole application. You don't need to know more about ZIO Test than that page teaches.
We test a small order service that has three collaborators: a repository that stores orders, a price list, and a notifier that tells the customer. The service is simple on purpose. What matters is how each test is written.
Learning Objectivesโ
By the end of this tutorial, you will understand:
- How to write a test double that records its calls in a
Refand hands them back to the test - How to test the error channel with
ZIO#exitandZIO#flip - How to test timeouts and retries without waiting, with
TestClock.adjustand a forked fiber - How to write a generator for a domain type and check a property of it with
check - How
Spec#provideSomeandSpec#provideShareddecide which state is fresh and which is shared - How
TestAspect.nonFlaky,TestAspect.timeoutandTestAspect.withLiveClockchange how a test runs - How to run one spec or one test from sbt
We'll learn these concepts through:
- The application under test
- A test double that records calls
- Testing success
- Testing failure
- Testing time
- Testing with generated inputs
- Sharing an expensive layer
- Changing how tests run with test aspects
- Running one spec or one test
- Putting it together
We recommend reading from top to bottom. Each section builds on the one before.
Backgroundโ
An application test has two jobs. It must check what the code returns, and it must check what the code does to the things around it: the repository it saves to and the notifier it calls. Real collaborators make tests slow and unpredictable, so a test replaces them with test doubles, small stand-ins that the test controls.
ZIO helps with this in two ways. Services are passed as layers, so a test can supply a different layer. And the clock, the console and the random number generator are services too, so a test can replace them as well. Time then moves only when the test says so.
Setupโ
The example needs ZIO and ZIO Test:
// ZIO core
libraryDependencies += "dev.zio" %% "zio" % "2.1.27"
// ZIO Test: the test library (test scope)
libraryDependencies += "dev.zio" %% "zio-test" % "2.1.27" % Test
// ZIO Test sbt integration (test scope)
libraryDependencies += "dev.zio" %% "zio-test-sbt" % "2.1.27" % Test
The complete project is in zio-examples/test-a-zio-application. Application code is in src/main/scala/testapp and the specs are in src/test/scala/testapp.
1. The Application Under Testโ
An order is a list of items, each with a product code (sku) and a quantity. The total is in cents, to avoid rounding questions. The domain file also lists everything that can go wrong when placing an order:
package testapp
final case class OrderId(value: Int)
final case class Item(sku: String, quantity: Int)
final case class Order(id: OrderId, items: List[Item], totalCents: Int)
/**
* What the caller gets back: the saved order and whether the customer was told
* about it.
*/
final case class Receipt(order: Order, notified: Boolean)
sealed trait OrderError extends Product with Serializable
object OrderError {
case object EmptyOrder extends OrderError
final case class InvalidQuantity(sku: String) extends OrderError
final case class UnknownProduct(sku: String) extends OrderError
final case class DuplicateOrder(id: OrderId) extends OrderError
}
final case class NotifyError(reason: String)
The repository saves orders and refuses an id it has already seen. Its in-memory version keeps them in a Ref:
package testapp
import zio._
trait OrderRepo {
def save(order: Order): IO[OrderError.DuplicateOrder, Unit]
def find(id: OrderId): UIO[Option[Order]]
}
final case class InMemoryOrderRepo(orders: Ref[Map[OrderId, Order]]) extends OrderRepo {
def save(order: Order): IO[OrderError.DuplicateOrder, Unit] =
orders.modify { current =>
if (current.contains(order.id)) (ZIO.fail(OrderError.DuplicateOrder(order.id)), current)
else (ZIO.unit, current + (order.id -> order))
}.flatten
def find(id: OrderId): UIO[Option[Order]] =
orders.get.map(_.get(id))
}
object InMemoryOrderRepo {
val layer: ULayer[OrderRepo] =
ZLayer.fromZIO(Ref.make(Map.empty[OrderId, Order]).map(InMemoryOrderRepo(_)))
}
The Notifier tells the customer about an order. The real one here only prints, after a 100-millisecond pause that stands for a network call:
package testapp
import zio._
trait Notifier {
def orderPlaced(order: Order): IO[NotifyError, Unit]
}
/** A notifier that "sends" a message by printing it. */
object ConsoleNotifier extends Notifier {
def orderPlaced(order: Order): IO[NotifyError, Unit] =
ZIO.sleep(100.millis) *> ZIO.debug(s"email: order ${order.id.value} received, total ${order.totalCents} cents")
val layer: ULayer[Notifier] = ZLayer.succeed(ConsoleNotifier)
}
The PriceList knows the price of each product. Loading it is the slow step of starting the application, so it is a scoped layer: it loads once, and it is closed when the scope ends. We print a message at both points to watch it in Section 7:
package testapp
import zio._
final case class PriceList(prices: Map[String, Int]) {
def priceOf(sku: String): Option[Int] = prices.get(sku)
}
object PriceList {
/**
* Loading the price list is the slow, expensive step of starting the
* application.
*/
val layer: ZLayer[Any, Nothing, PriceList] =
ZLayer.scoped {
ZIO.acquireRelease(
ZIO.debug("loading price list") *> ZIO.succeed(PriceList(Map("apple" -> 50, "bread" -> 250, "cheese" -> 800)))
)(_ => ZIO.debug("closing price list"))
}
}
OrderService ties them together. It rejects a bad order, saves a good one, and then tries to notify the customer:
package testapp
import zio._
final case class OrderService(repo: OrderRepo, notifier: Notifier, prices: PriceList) {
def place(id: OrderId, items: List[Item]): IO[OrderError, Receipt] =
for {
_ <- ZIO.fail(OrderError.EmptyOrder).when(items.isEmpty)
_ <- ZIO.foreachDiscard(items)(validate)
total <- ZIO.foreach(items)(lineTotal).map(_.sum)
order = Order(id, items, total)
_ <- repo.save(order)
notified <- notify(order)
} yield Receipt(order, notified)
private def validate(item: Item): IO[OrderError, Unit] =
ZIO.fail(OrderError.InvalidQuantity(item.sku)).when(item.quantity <= 0).unit
private def lineTotal(item: Item): IO[OrderError, Int] =
ZIO
.fromOption(prices.priceOf(item.sku))
.mapBoth(_ => OrderError.UnknownProduct(item.sku), _ * item.quantity)
/**
* Tries for at most 2 seconds per attempt and at most 3 attempts, one second
* apart. A saved order is never lost because the customer could not be told.
*/
private def notify(order: Order): UIO[Boolean] =
notifier
.orderPlaced(order)
.timeoutFail(NotifyError("timed out"))(2.seconds)
.retry(Schedule.spaced(1.second) && Schedule.recurs(2))
.as(true)
.orElse(ZIO.succeed(false))
}
object OrderService {
val layer: URLayer[OrderRepo with Notifier with PriceList, OrderService] =
ZLayer.fromFunction(OrderService.apply _)
}
The service has three rules for the notification. Each attempt may take at most 2 seconds. A failed attempt is retried after 1 second, up to 2 more times. If all 3 attempts fail, the order stays saved and the receipt says notified = false. These rules are the hard part to test, because they depend on time.
2. A Test Double That Records Callsโ
To test OrderService we need a Notifier that we can tell what to do, and that remembers what it was asked. Here is one:
package testapp
import zio._
/**
* A test double: records every call in a `Ref` and decides what each call does.
*/
final class FakeNotifier(calls: Ref[Vector[OrderId]], behave: Int => IO[NotifyError, Unit]) {
/**
* The `Notifier` that the code under test sees. `behave` gets the number of
* this call, counting from 1.
*/
val notifier: Notifier = new Notifier {
def orderPlaced(order: Order): IO[NotifyError, Unit] =
calls.updateAndGet(_ :+ order.id).flatMap(all => behave(all.size))
}
def recorded: UIO[Vector[OrderId]] = calls.get
}
object FakeNotifier {
/** Every call succeeds at once. */
val succeeding: Int => IO[NotifyError, Unit] = _ => ZIO.unit
/**
* The layer provides the double both as a `Notifier`, for the code under
* test, and as itself, for the test.
*/
def layer(behave: Int => IO[NotifyError, Unit]): ULayer[Notifier with FakeNotifier] =
ZLayer.fromZIOEnvironment {
Ref.make(Vector.empty[OrderId]).map { calls =>
val fake = new FakeNotifier(calls, behave)
ZEnvironment[Notifier, FakeNotifier](fake.notifier, fake)
}
}
/** The order ids the notifier was called with, oldest first. */
val calls: URIO[FakeNotifier, Vector[OrderId]] =
ZIO.serviceWithZIO[FakeNotifier](_.recorded)
}
This file is in src/test, so it is not part of the application. It works like this:
callsis aRefthat holds the id of each order the notifier was called with. Each call adds one, atomically, even when calls run on different fibersbehaveis a function from the number of this call, counting from 1, to what the call does.FakeNotifier.succeedingalways succeeds. Section 5 passes functions that fail or never answernotifieris what the service sees: a plainNotifierthat records the call and then runsbehaveFakeNotifier.layerbuilds the double and puts two things into the environment, theNotifierand the double itself, so the test can read the recorded callsFakeNotifier.callsis a shortcut that a test uses to read them
FakeNotifier does not extend Notifier on purpose. ZLayer wiring finds a service by its type, and a layer that provided both a Notifier and a subclass of it would make provide report that Notifier is provided twice.
3. Testing Successโ
The tests for OrderService are in OrderServiceSpec. We look at its first suite here:
package testapp
import zio._
import zio.test._
object OrderServiceSpec extends ZIOSpecDefault {
val apples = List(Item("apple", 4))
def spec =
suite("OrderService")(
suite("one order at a time")(
suite("placing an order")(
test("saves the order and tells the customer") {
for {
receipt <- ZIO.serviceWithZIO[OrderService](_.place(OrderId(1), List(Item("apple", 4), Item("bread", 1))))
saved <- ZIO.serviceWithZIO[OrderRepo](_.find(OrderId(1)))
calls <- FakeNotifier.calls
} yield assertTrue(
receipt.order.totalCents == 450,
receipt.notified,
saved.contains(receipt.order),
calls == Vector(OrderId(1))
)
},
test("starts every test with an empty repository") {
for {
saved <- ZIO.serviceWithZIO[OrderRepo](_.find(OrderId(1)))
} yield assertTrue(saved.isEmpty)
}
),
suite("rejecting an order")(
test("an empty order fails with EmptyOrder") {
for {
exit <- ZIO.serviceWithZIO[OrderService](_.place(OrderId(2), Nil)).exit
} yield assertTrue(exit == Exit.fail(OrderError.EmptyOrder))
},
test("a zero quantity fails with InvalidQuantity") {
for {
error <- ZIO.serviceWithZIO[OrderService](_.place(OrderId(3), List(Item("apple", 0)))).flip
} yield assertTrue(error == OrderError.InvalidQuantity("apple"))
},
test("an unknown product fails with UnknownProduct") {
for {
error <- ZIO.serviceWithZIO[OrderService](_.place(OrderId(4), List(Item("truffle", 1)))).flip
} yield assertTrue(error == OrderError.UnknownProduct("truffle"))
},
test("a rejected order is neither saved nor announced") {
for {
_ <- ZIO.serviceWithZIO[OrderService](_.place(OrderId(5), List(Item("truffle", 1)))).ignore
saved <- ZIO.serviceWithZIO[OrderRepo](_.find(OrderId(5)))
calls <- FakeNotifier.calls
} yield assertTrue(saved.isEmpty, calls.isEmpty)
},
test("placing the same order twice fails with DuplicateOrder") {
for {
service <- ZIO.service[OrderService]
_ <- service.place(OrderId(6), apples)
error <- service.place(OrderId(6), apples).flip
calls <- FakeNotifier.calls
} yield assertTrue(error == OrderError.DuplicateOrder(OrderId(6)), calls.size == 1)
}
)
).provideSome[PriceList](
OrderService.layer,
InMemoryOrderRepo.layer,
FakeNotifier.layer(FakeNotifier.succeeding)
),
test("two orders with the same id placed at once: exactly one wins") {
for {
service <- ZIO.service[OrderService]
exits <- ZIO.collectAllPar(List.fill(2)(service.place(OrderId(7), apples).exit))
calls <- FakeNotifier.calls
} yield assertTrue(exits.count(_.isSuccess) == 1, calls.size == 1)
}.provideSome[PriceList](
OrderService.layer,
InMemoryOrderRepo.layer,
FakeNotifier.layer(FakeNotifier.succeeding)
) @@ TestAspect.nonFlaky(50)
).provideShared(PriceList.layer)
}
Look at the first test, saves the order and tells the customer. It does three things that a test of application code usually does:
- It calls the service with
ZIO.serviceWithZIO[OrderService], the way the rest of the program would - It reads the effect of the call from the repository,
find, instead of trusting the return value alone - It reads the recorded calls from the double with
FakeNotifier.callsand checks that exactly one order was announced
The tests get their services from provideSome at the end of the suite. provideSome[PriceList] means "provide these layers, and leave PriceList for someone else". Without the type parameter, provide would report PriceList as a missing layer. Sections 6 and 7 explain who supplies it.
Spec#provideSome builds the layers again for every test. The second test, starts every test with an empty repository, shows the result: it looks for order 1, which the first test saved, and does not find it. Tests do not see each other's state, in whatever order they run.
4. Testing Failureโ
A failure is a value in the error channel, so a test can inspect it like any other result. The tests in the rejecting an order suite use two ways to look at one.
ZIO#exit turns the effect into one that always succeeds, with an Exit as its value. The test then compares the Exit with the one it expects, Exit.fail(OrderError.EmptyOrder). This also catches a defect or an interruption, because an Exit can hold any of them:
exit <- ZIO.serviceWithZIO[OrderService](_.place(OrderId(2), Nil)).exit
// ...
assertTrue(exit == Exit.fail(OrderError.EmptyOrder))
ZIO#flip swaps the error and success channels. A failure becomes the value, and a success becomes a failure, which fails the test with the unexpected success as its error. When the test only cares about the error, flip reads best:
error <- ZIO.serviceWithZIO[OrderService](_.place(OrderId(3), List(Item("apple", 0)))).flip
// ...
assertTrue(error == OrderError.InvalidQuantity("apple"))
A failure test should also check what did not happen. a rejected order is neither saved nor announced places an order with an unknown product and then checks that the repository is empty and the double recorded no calls.
Run the spec with sbt "testOnly testapp.OrderServiceSpec". The output is:
+ OrderService
+ one order at a time
+ placing an order
loading price list
+ saves the order and tells the customer
+ starts every test with an empty repository
+ rejecting an order
+ a rejected order is neither saved nor announced
+ an unknown product fails with UnknownProduct
+ an empty order fails with EmptyOrder
+ a zero quantity fails with InvalidQuantity
+ placing the same order twice fails with DuplicateOrder
+ two orders with the same id placed at once: exactly one wins - repeated: 50
closing price list
8 tests passed. 0 tests failed. 0 tests ignored.
Tests inside a suite run in parallel, so the order of the lines can differ from run to run.
5. Testing Timeโ
The notification rules involve timeouts and waits, and a test that really waited 8 seconds would be slow. In a test, TestClock replaces the real clock. Time stands still until the test calls TestClock.adjust, which moves the clock forward and runs everything that was due.
The pattern is the one from Writing Tests: start the code on its own fiber with ZIO#fork, adjust the clock, and join the fiber. Here is NotificationSpec:
package testapp
import zio._
import zio.test._
object NotificationSpec extends ZIOSpecDefault {
val apples = List(Item("apple", 4))
def place(id: Int): ZIO[OrderService, OrderError, Receipt] =
ZIO.serviceWithZIO[OrderService](_.place(OrderId(id), apples))
def spec =
suite("Notification")(
test("a notifier that fails twice is retried, one second apart") {
for {
fiber <- place(1).fork
_ <- TestClock.adjust(1.second)
early <- fiber.poll
calls1 <- FakeNotifier.calls
_ <- TestClock.adjust(1.second)
result <- fiber.join
calls3 <- FakeNotifier.calls
} yield assertTrue(early.isEmpty, calls1.size == 2, result.notified, calls3.size == 3)
}.provideSome[PriceList](
OrderService.layer,
InMemoryOrderRepo.layer,
FakeNotifier.layer(attempt => ZIO.fail(NotifyError("down")).when(attempt < 3).unit)
),
test("a notifier that never answers is given up on, and the order is still saved") {
for {
fiber <- place(2).fork
_ <- TestClock.adjust(8.seconds)
receipt <- fiber.join
saved <- ZIO.serviceWithZIO[OrderRepo](_.find(OrderId(2)))
calls <- FakeNotifier.calls
} yield assertTrue(!receipt.notified, saved.contains(receipt.order), calls.size == 3)
}.provideSome[PriceList](
OrderService.layer,
InMemoryOrderRepo.layer,
FakeNotifier.layer(_ => ZIO.never)
),
test("the real console notifier works on the live clock") {
for {
receipt <- place(3)
} yield assertTrue(receipt.notified)
}.provideSome[PriceList](
OrderService.layer,
InMemoryOrderRepo.layer,
ConsoleNotifier.layer
) @@ TestAspect.withLiveClock
).provideShared(PriceList.layer) @@ TestAspect.timeout(10.seconds)
}
The first test passes a behave function that fails the first two calls and lets the third succeed. The service retries after 1 second, so the test:
- forks
place(1), which makes the first attempt and fails at once - adjusts the clock by 1 second, which wakes the retry, and checks with
Fiber#pollthat the fiber has not finished yet and that the double has seen 2 calls - adjusts the clock by 1 more second, joins the fiber, and checks that the third attempt succeeded
The second test passes _ => ZIO.never: the notifier never answers. Each attempt then ends at the 2-second timeout, and the waits between attempts add up to 8 seconds: 2 + 1 + 2 + 1 + 2. The test adjusts the clock by 8 seconds and checks three results: the receipt says notified = false, the order is saved, and the double saw 3 calls. The whole test takes a few milliseconds.
The third test is different. It uses ConsoleNotifier, the real notifier, which pauses with ZIO.sleep(100.millis). On TestClock that sleep never ends unless someone adjusts the clock, so the test would hang. The test aspect TestAspect.withLiveClock gives this one test the real clock. We see in Section 8 what happens without it.
Run the second test alone with sbt 'testOnly testapp.NotificationSpec -- -t "never answers"'. The output is:
+ Notification
loading price list
+ a notifier that never answers is given up on, and the order is still saved
closing price list
1 tests passed. 0 tests failed. 0 tests ignored.
For more on TestClock, such as setTime and sleeping fibers, see TestClock.
6. Testing with Generated Inputsโ
So far each test used one order that we chose. A property test states a rule that must hold for every input, and the framework tries many generated inputs. The generator for a domain type is built from smaller generators:
package testapp
import zio.test._
/** Generators for the domain types. */
object OrderGen {
val orderId: Gen[Any, OrderId] = Gen.int(1, 1000000).map(OrderId(_))
val knownSku: Gen[Any, String] = Gen.elements("apple", "bread", "cheese")
val validItem: Gen[Any, Item] =
for {
sku <- knownSku
quantity <- Gen.int(1, 10)
} yield Item(sku, quantity)
val validItems: Gen[Any, List[Item]] = Gen.listOfBounded(1, 5)(validItem)
val badQuantityItem: Gen[Any, Item] =
for {
sku <- knownSku
quantity <- Gen.int(-5, 0)
} yield Item(sku, quantity)
}
Gen.int(1, 1000000)produces integers in a range, andmap(OrderId(_))wraps them in our typeGen.elements("apple", "bread", "cheese")picks one of the listed values- A
forcomprehension combines two generators, here a product code and a quantity, into a generator ofItem Gen.listOfBounded(1, 5)produces lists with 1 to 5 elements of a given generator
Now the properties:
package testapp
import zio._
import zio.test._
object OrderPropertySpec extends ZIOSpecDefault {
/**
* One fresh service stack per call, so that every generated sample starts
* from an empty repository.
*/
def freshService[A](use: OrderService => ZIO[OrderRepo, OrderError, A]): ZIO[PriceList, OrderError, A] =
ZIO
.serviceWithZIO[OrderService](use)
.provideSome[PriceList](OrderService.layer, InMemoryOrderRepo.layer, FakeNotifier.layer(FakeNotifier.succeeding))
def spec =
suite("Order properties")(
test("the total is the sum of price times quantity, and the order can be found again") {
check(OrderGen.orderId, OrderGen.validItems) { (id, items) =>
for {
prices <- ZIO.service[PriceList]
receipt <- freshService(_.place(id, items))
expected = items.map(item => prices.priceOf(item.sku).get * item.quantity).sum
} yield assertTrue(receipt.order == Order(id, items, expected), receipt.notified)
}
},
test("any item with a quantity below one rejects the whole order") {
check(OrderGen.orderId, OrderGen.validItems, OrderGen.badQuantityItem) { (id, items, bad) =>
for {
error <- freshService(_.place(id, items :+ bad)).flip
} yield assertTrue(error == OrderError.InvalidQuantity(bad.sku))
}
}
).provideShared(PriceList.layer)
}
check takes one generator for each input and a function that returns a test result. It runs the function on 200 generated values by default. If one fails, ZIO Test looks for a smaller input that still fails, a step called shrinking, and reports that one.
The first property says that the total of the order is the sum of price times quantity, computed here from the price list in the test, whatever the items are. The second says that adding one item with a quantity below one to any valid list rejects the whole order.
Pay attention to freshService. Section 3 said that provideSome builds the layers again for each test, but a property test is one test that runs the function 200 times. If the function used the repository from the test's layers, every generated value would share one repository, and the test would fail with DuplicateOrder whenever two generated order ids were the same. So each generated value gets its own service stack, built with provideSome on the effect inside check.
7. Sharing an Expensive Layerโ
The PriceList layer is the expensive one. Every spec needs it, and nothing in a test changes it, so there is no reason to load it for each test.
Look at the end of each spec: .provideShared(PriceList.layer). While provide and provideSome build their layers for each test, provideShared builds its layer once for the whole spec and shares it with every test. The layer is closed when the last test is done.
The output of the earlier sections shows it. The price list was loaded once and closed once for the whole OrderServiceSpec, which ran 8 tests, one of them repeated:
loading price list
...
closing price list
This gives a rule for choosing between the two:
| Layer | Use | Why |
|---|---|---|
| Slow to build, never changed by tests | provideShared | It is built once for the spec |
| Holds state that a test changes or records | provide / provideSome | Every test starts from a clean state |
The two combine, as OrderServiceSpec shows: provideSome[PriceList] on the suite leaves the price list open, and provideShared on the outside fills it in.
A shared layer is shared state. If a test changes something in it, other tests can see the change, and the result can depend on the order the tests run in. Put only read-only or safe-to-share resources in provideShared.
8. Changing How Tests Run with Test Aspectsโ
A test aspect wraps a test or a suite and changes how it runs, written with @@. The example uses three.
TestAspect.nonFlaky(50) runs a test again and again, 51 times when it passes, and stops at the first failure. It is made for tests of concurrent code, where a failure may show up only now and then. The last test of OrderServiceSpec starts two placements of the same order at the same moment and expects that exactly one wins. The repository takes the decision inside one atomic Ref#modify, which is why the test passes every time. The report shows repeated: 50.
The order of provideSome and @@ matters here. The test is written as test(...).provideSome(...) @@ TestAspect.nonFlaky(50), so the aspect wraps a test that builds its layers inside. Each run gets a new repository. With the aspect applied first and provide outside, all the runs share one repository, and every run after the first finds order 7 already saved. We tried it, and the check fails with:
0 was not equal to 1
exits.count(_.isSuccess) == 1
TestAspect.timeout(10.seconds) fails a test that takes longer than 10 seconds. NotificationSpec applies it to the whole suite. A test that waits for a clock nobody moves would otherwise hang the build forever. The timeout is measured in real time, not on the TestClock.
TestAspect.withLiveClock gives a test the real clock, as in Section 5. If we remove it from the third test and use a 3-second timeout, the test fails with:
- the real console notifier works on the live clock
Timeout of 3 s exceeded.
Both together show a good habit: use withLiveClock only on the tests that need real time, and keep a timeout on the suite so that a mistake fails the test instead of hanging the build.
Test Aspects lists all of them, including flaky, retries, ignore and sequential.
9. Running One Spec or One Testโ
sbt test runs every spec. During development you usually want less.
testOnly runs one spec, given by its class name. Here it runs NotificationSpec only:
sbt "testOnly testapp.NotificationSpec"
The option -t after -- runs the tests whose label contains a given text. The label is joined to the labels of the enclosing suites, so -t can also pick a whole suite. This command runs one test of OrderServiceSpec:
sbt 'testOnly testapp.OrderServiceSpec -- -t "an empty order fails with EmptyOrder"'
The output is:
+ OrderService
+ one order at a time
+ rejecting an order
loading price list
+ an empty order fails with EmptyOrder
closing price list
1 tests passed. 0 tests failed. 0 tests ignored.
Notice that the shared price list is still loaded, but only once. Running Tests lists all the options.
10. Putting It Togetherโ
The whole suite is the three specs above. It differs from the first test you wrote in these ways:
- The code under test has three collaborators, and each test replaces the ones it cares about with doubles it controls
- Tests of failure check the error value and also what did not happen
- Time is moved by the test, so a test of 8 seconds of retries takes milliseconds
- Inputs come from generators of domain types, and each generated value starts from clean state
- The expensive layer is built once, the stateful layers once per test
Run all 13 tests from the zio-examples/test-a-zio-application folder with sbt test. The output is:
+ OrderService
+ one order at a time
+ placing an order
loading price list
loading price list
loading price list
+ starts every test with an empty repository
+ saves the order and tells the customer
+ rejecting an order
+ a rejected order is neither saved nor announced
+ an unknown product fails with UnknownProduct
+ an empty order fails with EmptyOrder
+ a zero quantity fails with InvalidQuantity
+ placing the same order twice fails with DuplicateOrder
email: order 3 received, total 200 cents
closing price list
+ two orders with the same id placed at once: exactly one wins - repeated: 50
closing price list
+ Notification
+ a notifier that never answers is given up on, and the order is still saved
+ a notifier that fails twice is retried, one second apart
+ the real console notifier works on the live clock
+ Order properties
+ any item with a quantity below one rejects the whole order
+ the total is the sum of price times quantity, and the order can be found again
closing price list
13 tests passed. 0 tests failed. 0 tests ignored.
sbt test runs the three specs at the same time, so they interleave, and each one loads its own price list: three loading price list lines, three closing price list lines. The summary counts the repeats of the concurrency test as one test.
Running the Examplesโ
All code from this tutorial is in zio-examples/test-a-zio-application. From that folder, sbt test runs the specs and sbt "runMain testapp.Main" runs the application itself, which places one order with the real notifier.
What You've Learnedโ
In this tutorial, you learned:
- How a test double records its calls in a
Ref, is exposed through a layer, and lets the test check what the code did - How to test the error channel with
ZIO#exitandZIO#flip, and how to check that nothing else happened - How to test timeouts and retries with a forked fiber and
TestClock.adjust, without waiting - How to build a generator for a domain type and check a property with
check, with fresh state for every generated value - How
provideSomegives every test fresh state, howprovideSharedbuilds an expensive layer once, and how the two combine - How
nonFlaky,timeoutandwithLiveClockchange how a test runs, and why@@goes afterprovideSome - How to run one spec with
testOnlyand one test with-t
Where to Go Nextโ
- To learn more about each test service, read Test Services
- To go deeper on generators and
check, read Property-Based Testing - To see every aspect, read Test Aspects
- To learn how retries and repeats are described, read Retry and Repeat Policies with Schedule