Search⌘ K

Unit Tests for Products Routes Part 3

Explore how to create and execute unit tests for product-related HTTP routes in Scala using pure functional programming techniques. Understand testing with valid and garbage JSON data, test repository behavior, and streaming responses to ensure your API handles products correctly.

Create a product

Before we work on our Products Routes tests, we need to adapt the code to create a product using the knowledge we gained from our Product Route update test.

Scala
casereq @POST -> Root/ "products" =>
req
.as[Product]
.flatMap { p =>
for {
cnt <- repo.saveProduct(p)
res <- cnt match {
case 0 => NotFound()
case _ => InternalServerError()
}
} yield res
}
.handleErrorWith {
case InvalidMessageBodyFailure(_, _) => BadRequest()
}

Garbage values

Moving on to our tests: We will start with sending garbage JSON via the POST request.

Scala
val expected StatusCode = Status.BadRequest
s"return$expectedStatusCode"in{
def service: HttpRoutes[IO] =
Router("/" -> new ProductsRoutes(emptyRepository).routes)
val payload = scala.util.Random.alphanumeric.take(256).mkString
val response: IO[Response[IO]] = service.orNotFound.run(
Request(method = Method.POST, uri = Uri.uri("/products"))
.withEntity(payload.asJson.noSpaces)
)
val result = response.unsafeRunSync
result.status must be(expectedStatusCode)
result.body.compile.toVector.unsafeRunSync must be(empty)
}

There is nothing special here. The test is the same as for the Product Routes except for the changed URI and HTTP method. The code is also a bit ...