Unit Tests for Product Routes Part 2
Learn how to test the endpoints for updating an existing and a non-existent product.
We'll cover the following...
Updating with garbage values
Press + to interact
val expected StatusCode = Status.BadRequests"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 payload = scala.util.Random.alphanumeric.take(256).mkString val response: IO[Response[IO]] = service.orNotFound.run(Request(method = Method.PUT, uri = u) .withEntity(payload.asJson.noSpaces))val result = response.unsafeRunSyncresult.status must be(expectedStatusCode) result.body.compile.toVector.unsafeRunSync must be(empty)}}
Here, we are testing our update product functionality with garbage JSON values. This test should return 400 Bad Request
. However, if we run our test, we get an exception instead:
Press + to interact
[info] when PUT /product/ID[info] when request body is invalid[info] - must return 400 Bad Request *** FAILED ***[info] InvalidMessageBodyFailure was thrown during property[info] Occurred when passed generated values ([info] id = 932682c9-1f9a-463a-84db-a0992d466aa3[info] )
So let’s take a deep breath and look at our code:
Press + to interact
case req @ PUT -> Root / "product" / UUIDVar(id) => for{p <- req.as[Product]_ <- repo.updateProduct(p)r <- NoContent()} yield r
As we can see, we have done no error handling at all. So maybe we should rewrite this a ...
Access this course and 1400+ top-rated courses and projects.