Skip to main content
Version: 2.x

Derivation of ZIO Test Generators

Introductionโ€‹

ZIO Test supports property-based testing via the Gen type. Gen[R, A] is a random generator of values of type A. Such a generator can be used to produce test cases for a property, which can then be checked for validity. The zio-schema-zio-test module provides a way to derive a Gen[R, A] from a Schema[A]. In this section, we will see how this functionality works.

Installationโ€‹

In order to derive a generator from a ZIO Schema, we need to add the following dependency to our build.sbt file:

libraryDependencies += "dev.zio" %% "zio-schema-zio-test" % 1.7.5

DriveGenโ€‹

The DriveGen inside zio.schema package provides the gen operator which takes a Schema[A] implicitly and returns a Gen[Sized, A]:

object DeriveGen {
def gen[A](implicit schema: Schema[A]): Gen[Sized, A] = ???
}

Exampleโ€‹

In the following example, we will derive a generator for the Person class using the DeriveGen.gen operator:

import zio.schema.{DeriveGen, DeriveSchema, Schema}
import zio.test.{Gen, Sized}

case class Person(name: String, age: Int)

object Person {
implicit val schema: Schema[Person] = DeriveSchema.gen
val gen: Gen[Sized, Person] = DeriveGen.gen
}

import zio.test._

object ExampleSpec extends ZIOSpecDefault {
def spec =
test("example test") {
check(Person.gen) { p =>
assertTrue(???)
}
}
}

ZIO Chat

๐ŸŒŸ Greetings from ZIO Chat! ๐ŸŒŸ Have questions about ZIO? Look no further! I'm here to be your ZIO guru. Whether you're a seasoned pro or just starting out, I've got answers tailored just for you. Fire away with your ZIO queries, and I'll hit you back with the best insights I've got. Let's dive into the world of ZIO together!