Skip to main content
Version: 2.x

Writing Tests

ZIO comes with its own test framework, ZIO Test. A test in ZIO Test is an effect, so it can use everything from the previous pages: services, resources, fibers and time. This page shows how to write and run a first test.

Installationโ€‹

To use ZIO Test, add the zio-test and zio-test-sbt artifacts to build.sbt, in the Test scope:

// 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

sbt 1.8.0 and later find ZIO Test on their own. With an older sbt version, also add this line:

testFrameworks += new TestFramework("zio.test.sbt.ZTestFramework")

A First Specโ€‹

A spec is an object that extends ZIOSpecDefault and defines spec, a tree of tests. suite groups tests under a name, and test defines one test, whose body is an effect that ends with an assertion. assertTrue takes ordinary Boolean expressions and, when one is false, reports the values that made it false:

import zio._
import zio.test._

object GreetingSpec extends ZIOSpecDefault {
def spec =
suite("GreetingSpec")(
test("builds a greeting") {
for {
greeting <- ZIO.succeed("Hello, Ada!")
} yield assertTrue(greeting.startsWith("Hello"), greeting.length == 11)
}
)
}

Specs go under src/test/scala. sbt test runs all of them, and sbt "testOnly GreetingSpec" runs one.

Test Servicesโ€‹

Inside a test, the standard ZIO services are replaced by test versions that the test controls. Two of them matter most when starting out.

TestConsole records what the program prints and supplies the lines it reads. TestConsole.feedLines queues input, and TestConsole.output returns everything printed so far, one entry per print, with the line break that Console.printLine adds:

import zio._
import zio.test._

object ConsoleSpec extends ZIOSpecDefault {
val askName: ZIO[Any, java.io.IOException, Unit] =
for {
_ <- Console.printLine("What is your name?")
name <- Console.readLine
_ <- Console.printLine(s"Hello, $name!")
} yield ()

def spec =
test("greets the user by name") {
for {
_ <- TestConsole.feedLines("Ada")
_ <- askName
output <- TestConsole.output
} yield assertTrue(output == Vector("What is your name?\n", "Hello, Ada!\n"))
}
}

TestClock controls time. In a test, time stands still until the test moves it forward with TestClock.adjust, so a test of a one-minute timeout finishes at once. The effect that waits must run on its own fiber, so that the test can adjust the clock while it waits:

import zio._
import zio.test._

object TimeoutSpec extends ZIOSpecDefault {
def spec =
test("a slow task times out after one minute") {
for {
fiber <- ZIO.sleep(5.minutes).timeout(1.minute).fork
_ <- TestClock.adjust(1.minute)
result <- fiber.join
} yield assertTrue(result.isEmpty)
}
}

Test Services describes TestRandom, TestSystem and the other test services.

Providing Servicesโ€‹

A test that needs services gets them the way a program does, from layers. Spec#provide works like ZIO#provide, on a single test or on a whole suite. This spec checks a shortened version of GreeterLive from Services and Layers against a stub UserRepo that knows one user:

import zio._
import zio.test._

trait UserRepo {
def findName(id: Int): Task[Option[String]]
}

final case class GreeterLive(repo: UserRepo) {
def greet(id: Int): Task[String] =
repo.findName(id).map(name => s"Hello, ${name.getOrElse("stranger")}!")
}

object GreeterSpec extends ZIOSpecDefault {
val stubRepo: ULayer[UserRepo] =
ZLayer.succeed(new UserRepo {
def findName(id: Int): Task[Option[String]] =
ZIO.succeed(if (id == 1) Some("Ada") else None)
})

val greeterLayer: URLayer[UserRepo, GreeterLive] =
ZLayer.fromFunction(GreeterLive(_))

def spec =
suite("GreeterSpec")(
test("greets a known user by name") {
for {
greeting <- ZIO.serviceWithZIO[GreeterLive](_.greet(1))
} yield assertTrue(greeting == "Hello, Ada!")
},
test("greets an unknown user as a stranger") {
for {
greeting <- ZIO.serviceWithZIO[GreeterLive](_.greet(2))
} yield assertTrue(greeting == "Hello, stranger!")
}
).provide(greeterLayer, stubRepo)
}

Spec#provide builds the layers again for each test, so tests do not share state. To build them once for the whole suite, use Spec#provideShared.

The ZIO Test section covers assertions, property-based testing with generators, and test aspects such as timeouts and retries.

Next Stepsโ€‹

If you are comfortable with writing tests, the next step is to learn about ZIO's performance.

ZIO Chat

Hi there! ๐Ÿ‘‹ I'm ZIO Chat, your friendly neighborhood ZIO expert. I'm here to help you navigate the world of ZIO. Whether you're a seasoned pro or just starting out, fire away with your ZIO questions. I will hit you back with the best insights I've got. Let's dive into the world of ZIO together!