Play WSClient, lesson 7: testing without the internet
Controller tests with hand-written fakes behind a trait, and client tests that run the real WSClient against an embedded Play server, covering every UpstreamError case without a network call.
Topic
A deep dive into the Play Framework's WSClient library. From basic GET requests to advanced features like streaming and custom configuration, discover how to build robust HTTP clients in Scala with this essential tool.
Controller tests with hand-written fakes behind a trait, and client tests that run the real WSClient against an embedded Play server, covering every UpstreamError case without a network call.
Moving base URLs, timeouts and API keys into application.conf, loading them into a typed case class, and adding a WSRequestFilter that tags every call with a correlation id and logs its status and duration.
Moving WSClient calls into client classes, then running them in parallel: why a Future starts when it is created, Future.traverse with best-effort or all-or-nothing results, and a batching benchmark I first got wrong.
Timeouts, DNS failures and refused connections turned into values with Play's WSClient: a sealed UpstreamError, a helper whose Future never fails, recover versus recoverWith, and EitherT to chain calls.
Writing to an upstream with Play's WSClient: a BodyParser on the Action reads the incoming body, a BodyWritable picks the outgoing Content-Type from the type, and neither appears in the routes file.
Decoding upstream JSON into Scala types with play-json: codecs in companion objects, as versus validate, checking status before shape, and a custom Reads that keeps the upstream's nesting out of your domain.
First steps with Play's WSClient in Scala: one dependency, an injected singleton client, immutable requests, and three GET endpoints that translate upstream statuses into a contract of their own.