Part 6: Your First Test
So far, we checked every change by starting the server and typing curl commands. That works, but it is slow and easy to forget. In this last part, we write tests with ZIO Test that check the same behaviour automatically.
Remember the idea from the overview: routes are a function from a request to a response. So a test does not need a server, a port or a network connection. It builds a Request, hands it to the routes, and checks the Response that comes back.
1. Add the Test Dependencies
ZIO Test is a separate library, needed only for tests. Add these lines to build.sbt:
// 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
testFrameworks += new TestFramework("zio.test.sbt.ZTestFramework")
The % Test suffix keeps both libraries out of the application itself, and the testFrameworks line tells sbt how to find and run ZIO tests. Tests live in their own folder, next to main: create src/test/scala/BooksAppSpec.scala. The code in the next four sections goes into that file, below one import zio.test._ and the import zio.http._ and import zio._ lines it needs.
2. Write the First Test
Our first test asks for book 1 and checks both the status and the decoded book. Routes#runZIO passes a request to the routes and returns the response as an effect:
import zio.test._
val getDune =
test("GET /books/1 returns Dune") {
for {
response <- BooksApp.routes.runZIO(Request.get("/books/1"))
book <- response.body.asJson[Book]
} yield assertTrue(
response.status == Status.Ok,
book.title == "Dune",
)
}
Line by line:
import zio.test._brings in ZIO Test:test,suite,assertTrueand the spec types.test("...") { ... }defines one test case with a readable name and a body that is a ZIO effect.Request.get("/books/1")builds the same request thatcurl localhost:8080/books/1sends.BooksApp.routes.runZIO(...)runs the matching handler and produces itsResponse, with no server involved.response.body.asJson[Book]decodes the JSON body with the schema ofBook, exactly as ourPOSThandler decodes request bodies.assertTrue(...)checks every condition; when one is false, ZIO Test reports which one and the values involved.
3. Test the Error Responses
Error responses are part of our API's contract, so they deserve tests too. An unknown id must answer 404 with a JSON message:
val unknownBook =
test("GET /books/42 returns 404 Not Found") {
for {
response <- BooksApp.routes.runZIO(Request.get("/books/42"))
error <- response.body.asJson[ApiError]
} yield assertTrue(
response.status == Status.NotFound,
error.message == "No book with id 42",
)
}
A request with query parameters needs a URL instead of a plain path string. URL.root / "books" builds the path, and URL#addQueryParam appends ?limit=abc:
val malformedLimit =
test("GET /books?limit=abc returns 400 Bad Request") {
val request = Request.get((URL.root / "books").addQueryParam("limit", "abc"))
for {
response <- BooksApp.routes.runZIO(request)
} yield assertTrue(response.status == Status.BadRequest)
}
4. Test a Change of State
Finally, let's check that a created book is saved. The test sends a POST with a JSON body, built with the same Body.json our handlers use, then fetches the new book by its id:
val createBook =
test("POST /books saves a new book") {
val newBook = NewBook("Snow Crash", "Neal Stephenson", 1992)
for {
created <- BooksApp.routes.runZIO(Request.post("/books", Body.json(newBook)))
book <- created.body.asJson[Book]
fetched <- BooksApp.routes.runZIO(Request.get(s"/books/${book.id}"))
} yield assertTrue(
created.status == Status.Created,
book.id == 4,
fetched.status == Status.Ok,
)
}
The test expects id 4, because it starts from the three initial books. The next section makes sure that is always true.
5. Collect the Tests in a Spec
A ZIO test file is an object that extends ZIOSpecDefault and defines spec. We group our tests in a suite and provide the services they need:
object BooksAppSpec extends ZIOSpecDefault {
def spec =
suite("BooksApp")(
getDune,
unknownBook,
createBook,
malformedLimit,
).provide(InMemoryBookRepo.layer, Scope.default)
}
Line by line:
object BooksAppSpec extends ZIOSpecDefaultmakes the object a test file that sbt finds and runs.suite("BooksApp")(...)groups the four tests under one name.Spec#providewithInMemoryBookRepo.layergives the tests theBookRepotheir routes need, exactly asZIO#provideinrungives it to the server.Spec#providebuilds the layer separately for each test, so every test starts with the same three books, and the book created in one test never leaks into another.Scope.defaultsatisfies the second requirement ofRoutes#runZIO: aScope, in which ZIO HTTP can open resources while it handles the request and close them afterwards. When the server runs our routes, it takes care of theScope; in a test, we provide one ourselves.
On this page, each test is a val so we can show it on its own. In BooksAppSpec.scala, you can just as well write the four test(...) calls directly inside suite("BooksApp")(...), which is what the companion file below does.
6. Run the Tests
Let's run the tests from the project folder:
sbt test
ZIO Test runs the four tests and reports each one (the order of the lines may vary, because tests run in parallel):
+ BooksApp
+ GET /books/42 returns 404 Not Found
+ GET /books/1 returns Dune
+ POST /books saves a new book
+ GET /books?limit=abc returns 400 Bad Request
4 tests passed. 0 tests failed. 0 tests ignored.
Try breaking the app on purpose to see a failure: change the message in the GET /books/{id} handler, run sbt test again, and read how ZIO Test points at the condition that failed and the values it compared.
Putting It Together
Our project now has the finished app from Part 5 in src/main/scala/BooksApp.scala and its tests in src/test/scala/BooksAppSpec.scala. The companion test file contains the same four tests as the sections above; the only difference is that they sit directly inside the suite instead of in separate vals:
//> using scala 2.13.18
//> using dep dev.zio::zio-http:3.12.0
//> using dep dev.zio::zio-test:2.1.26
//> using dep dev.zio::zio-test-sbt:2.1.26
//> using file ../../../../main/scala/example/restapi/BooksApp.scala
// Run from this folder: scala-cli test BooksAppSpec.scala
// Or from zio-http-example-rest-api-tutorial: sbt test
package example.restapi
import zio._
import zio.http._
import zio.test._
/**
* Build Your First REST API — Part 6: Your First Test
*
* Calls the routes of the finished app directly, without starting a server.
*/
object BooksAppSpec extends ZIOSpecDefault {
def spec =
suite("BooksApp")(
test("GET /books/1 returns Dune") {
for {
response <- BooksApp.routes.runZIO(Request.get("/books/1"))
book <- response.body.asJson[Book]
} yield assertTrue(
response.status == Status.Ok,
book.title == "Dune",
)
},
test("GET /books/42 returns 404 Not Found") {
for {
response <- BooksApp.routes.runZIO(Request.get("/books/42"))
error <- response.body.asJson[ApiError]
} yield assertTrue(
response.status == Status.NotFound,
error.message == "No book with id 42",
)
},
test("POST /books saves a new book") {
val newBook = NewBook("Snow Crash", "Neal Stephenson", 1992)
for {
created <- BooksApp.routes.runZIO(Request.post("/books", Body.json(newBook)))
book <- created.body.asJson[Book]
fetched <- BooksApp.routes.runZIO(Request.get(s"/books/${book.id}"))
} yield assertTrue(
created.status == Status.Created,
book.id == 4,
fetched.status == Status.Ok,
)
},
test("GET /books?limit=abc returns 400 Bad Request") {
val request = Request.get((URL.root / "books").addQueryParam("limit", "abc"))
for {
response <- BooksApp.routes.runZIO(request)
} yield assertTrue(response.status == Status.BadRequest)
},
).provide(InMemoryBookRepo.layer, Scope.default)
}
Running the Examples
All the code from this tutorial is in zio-http-example-rest-api-tutorial. Each part's version of BooksApp.scala is in its own package (example.restapi.part1 to example.restapi.part4; the finished app from part 5 is in example.restapi). From that folder, start any part with sbt "runMain example.restapi.part2.BooksApp" or the finished app with sbt "runMain example.restapi.BooksApp", and run the tests with sbt test. Each file also runs on its own with scala-cli run BooksApp.scala from its folder.
What You've Learned
Congratulations, you have built and tested your first REST API with ZIO HTTP! In this tutorial, you learned:
- How a ZIO HTTP server turns a request into a response: a
Routesvalue holds route patterns such asMethod.GET / "books" / int("id"), each paired with a handler, andServer.serveruns them - How to read path parameters with typed segments such as
int("id"), and query parameters withRequest#queryParam,Request#queryOrElseandRequest#query - How to send and receive JSON by deriving a
SchemawithDeriveSchema.genand usingBody.jsonandBody#asJson - How to share state between requests with a
BookReposervice backed by aRefand provided with aZLayer - How to turn typed failures into clear error responses, and how to test routes directly with
Routes#runZIO, without starting a server
You now have a solid foundation in ZIO HTTP. The next step is to apply it to the parts of a real service that this tutorial left out, such as middleware, authentication and documentation.
Where to Go Next
- Want to know more about routing? Read the
Routes,RoutePatternandPathCodecreference pages, which cover more path segment types, such asstringanduuid. - Want to know more about requests and responses? The
Request,ResponseandBodyreference pages list the other ways to read input and build answers. - Ready to test more? The how-to guide Testing HTTP Applications shows
TestClient,TestServerand more testing patterns. - Want to add logging, CORS or timeouts to every route? Read about middleware.
- Want an API description and a typed client for free? The declarative
EndpointAPI describes routes as data, from which ZIO HTTP generates OpenAPI documentation and clients.