Play WSClient, lesson 7: testing without the internet
Six lessons in, the project calls two public APIs, handles five kinds of upstream failure, and runs calls in parallel. I had verified all of it with curl against the live internet. That proves it worked once, on a day when JSONPlaceholder and httpbin were up and answered quickly. It says nothing about a 500, a timeout or malformed JSON, which are exactly the cases the UpstreamError model from lesson 4 exists for. This lesson adds tests at two levels, and none of them needs the network.
Stack as before: Play 3.0.12, Scala 2.13, Guice, scalatestplus-play 7.0. The code is commit 10be88c in zakariahere/play-wsclient-lessons, and it builds on the config work from lesson 6.
Two questions, two kinds of test
There are two separate things to check. The first is whether the controller does the right thing with each result: does a Left(Missing) become a 404, does best effort keep the good results and report the bad ones? That question does not involve HTTP at all. The second is whether the client turns each real HTTP situation into the right result: does a 500 become BadStatus, does a slow answer become TimedOut? That question is only about HTTP. Mixing the two leads to slow, fragile tests, so I wrote one spec for each.
Controller tests: depend on a trait
The controller injected the concrete JsonPlaceholderClient, whose constructor needs a WSClient and a Configuration. To replace it in a test, the controller has to depend on a contract instead. I extracted two small traits:
@ImplementedBy(classOf[JsonPlaceholderClient])
trait TodoApi {
def todo(id: Int): Upstream[Todo]
def user(id: Int): Upstream[UserSummary]
def todosFor(userId: Int): Upstream[Seq[Todo]]
def postsFor(userId: Int): Upstream[Seq[Post]]
}
class JsonPlaceholderClient @Inject()(ws: WSClient, config: Configuration)(implicit ec: ExecutionContext)
extends JsonHttp(ws, UpstreamConfig.load(config, "jsonplaceholder")) with TodoApi@ImplementedBy is Guice's default binding: when something asks for a TodoApi, Guice builds a JsonPlaceholderClient, without a module. The client is still a @Singleton, so a controller that asks for the concrete class gets the same instance. With compile-time DI, the components trait declares lazy val todoApi: TodoApi = new JsonPlaceholderClient(...), and a test components trait overrides it.

Because Upstream[A] is just Future[Either[UpstreamError, A]], a fake is ordinary Scala. Mine is backed by two maps and records every call it receives:
class FakeTodos(users: Map[Int, UserSummary], todos: Map[Int, Todo]) extends TodoApi {
val calls = new ConcurrentLinkedQueue[String]()
private def answer[A](call: String, found: Option[A]): Upstream[A] = {
calls.add(call)
Future.successful(found.toRight(Missing(s"fake:$call")))
}
def todo(id: Int): Upstream[Todo] = answer(s"todo/$id", todos.get(id))
def user(id: Int): Upstream[UserSummary] = answer(s"user/$id", users.get(id))
// todosFor and postsFor follow the same pattern
}
val controller = new ParallelController(fake, NoBin, stubControllerComponents())The call log is a ConcurrentLinkedQueue because the controller makes some calls in parallel, and a real implementation would record them from different threads. The controller is built with new and stubControllerComponents(), so there is no application, no Guice and no network. The six controller tests ran in about half a second together.
The test I find most useful pins down a trade-off from lesson 5. The profile endpoint creates three futures before combining them with EitherT, which saves latency and means all three calls run even when the first result is a 404:
"return 404 when the user is missing, and still make all three calls" in {
val fake = new FakeTodos(Map.empty, todos)
val result = controllerWith(fake).profile(99)(FakeRequest())
status(result) mustBe NOT_FOUND
(contentAsJson(result) \ "error").as[String] mustBe "not_found"
fake.calls.asScala.toSet mustBe Set("user/99", "todosFor/99", "postsFor/99")
}If someone later makes that endpoint sequential, this test fails, and the change has to be made on purpose. The other controller tests cover best effort (found and failed lists), all-or-nothing (every todo, or a 404 on the first missing id), and the mapping from each UpstreamError to its HTTP status.
Client tests: a real server on localhost
For the client, a fake would defeat the purpose. I want to test the real WSClient code, including status handling, JSON validation and the exception mapping in recover. Play can start a small server inside the test, with routes written in its sird DSL, on a random free port:
private def withFakeUpstream[T](block: JsonPlaceholderClient => T): T =
Server.withRouterFromComponents() { components =>
import components.{defaultActionBuilder => Action}
{
case GET(p"/todos/1") => Action(Ok(Json.obj("userId" -> 1, "id" -> 1, "title" -> "write tests", "completed" -> false)))
case GET(p"/todos/2") => Action(Ok(Json.obj("id" -> 2, "oops" -> "no title here")))
case GET(p"/todos/500") => Action(InternalServerError("database on fire"))
case GET(p"/todos/429") => Action(TooManyRequests("slow down"))
case GET(p"/todos/3") => Action.async {
delayed(2.seconds)(Future.successful(Ok(Json.obj())))(components.actorSystem)
}
}
} { implicit port =>
WsTestClient.withClient { ws =>
block(new JsonPlaceholderClient(ws, config(s"http://localhost:$port")))
}
}
private def config(baseUrl: String) = Configuration(
"upstreams.jsonplaceholder.base-url" -> baseUrl,
"upstreams.jsonplaceholder.timeout" -> "500 millis"
)This is where lesson 6 pays off. The base URL and timeout come from Configuration, so pointing the real client at the local server is one line, and the timeout can be 500 ms instead of 5 seconds. Without that, I would have had to mock WSClient, WSRequest and WSResponse, and the test would check my mock more than my code. The slow route uses Pekko's after to schedule its answer, so no server thread sleeps for two seconds.

UpstreamError cases, plus the happy path, without leaving the machine.The 404 case needs no route: an unknown path falls through to Play's default 404, which getJson maps to Missing. The Unreachable case needs no server at all. Port 1 has nothing listening, so the operating system refuses the connection immediately. The timeout test also checks the duration, so it fails if the configured timeout is ignored:
"turn a slow answer into TimedOut, after the configured 500ms" in withFakeUpstream { client =>
val start = System.nanoTime()
val result = await(client.todo(3))
val tookMs = (System.nanoTime() - start) / 1000000
result must matchPattern { case Left(TimedOut(_)) => }
tookMs must be < 1500L
}The logging filter from lesson 6 ran inside the tests too, and its output showed the request reaching the local server: jsonplaceholder GET http://localhost:32736/todos/1 -> 200 in 320ms.
What broke on the way

The first compile failed twice. play.api.test.Helpers._ exports GET as a String, for FakeRequest(GET, "/"), and play.api.routing.sird._ exports GET as an extractor for pattern matching. In a sird spec I now import only Helpers.{await, defaultAwaitTimeout}. The second error was TheAfterWord does not take parameters: ScalaTest's word specs define their own after, which shadows Pekko's. Renaming on import, {after => delayed}, fixed it.
The timeout test passed, but IntelliJ reported 2084 ms for it. The client gave up after 500 ms, and the assertion ran then. The rest of the time was spent shutting down the embedded server, which waited for the slow response it still owed. A client-side timeout stops my code from waiting, but it does not cancel anything on the upstream. That matters for the resilience lesson: retrying after a timeout can mean the upstream is now doing the same work twice.
One practical note: I ran the 13 tests through IntelliJ's ScalaTest runner, because my own sbt run was holding the build and a second sbt client just queued behind it. The specs are plain ScalaTest, so sbt test runs them the same way once the dev server is stopped.
What I take from lesson 7
- Test the controller and the client separately. One is about logic, the other about HTTP.
- Controllers depend on a trait. A hand-written fake is shorter than a mock and can record its calls.
- Turn deliberate trade-offs into tests, so changing them is a visible decision.
- Test the real client against
Server.withRouterFromComponents. Config-driven base URLs and timeouts make that one line. - A client timeout does not cancel the upstream's work. Keep that in mind before retrying.
Next: streaming. .stream(), Pekko Source[ByteString], proxying a large download without loading it into memory, and streaming uploads.