Search⌘ K

Unit Tests for Product Routes Part 1

Explore unit testing strategies for product routes in Scala HTTP APIs. Learn to handle requests for existing and non-existing products, create valid URIs, and validate status codes and response bodies. Understand the use of implicit JSON encoders and EntityDecoders in testing context.

Querying a non-existing product

Scala
val emptyRepository: Repository[IO] = new TestRepository[IO](Seq.empty)
val expectedStatusCode = Status.NotFound
s"return$expectedStatusCode"in{
forAll("id") { id: ProductId =>
Uri.fromString("/product/" + id.toString) match {
case Left(_) => fail("Could not generate valid URI!")
case Right(u) =>
def service: HttpRoutes[IO] =
Router("/" -> new ProductRoutes(emptyRepository).routes)
val response: IO[Response[IO]] = service.orNotFound.run(
Request(method = Method.GET, uri = u)
)
val result = response.unsafeRunSync
result.status must be(expectedStatusCode)
result.body.compile.toVector.unsafeRunSync must be(empty)
}
}
}

Above, you can see the test for querying a non-existing product. This must return an empty response using a 404 Not Found status code (Line 2).

First, we try to create a valid URI from our generated ProductId. If that is successful, we create a small service wrapper for our ...