

To assist with this, Play provides a sendResource method that allows easily creating results from files on the classpath.

It often will be better to capture an actual response from the service your testing, and return that. In the previous example, we built the json manually for the mocked service. Val result = Await.result(new GitHubClient(client, "").repositories(), 10.seconds) Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World"))) The client is very simple, it just allows you to look up the names of the public repositories: import Ĭlass GitHubClient(ws: WSClient, baseUrl: String)(implicit ec: ExecutionContext) def this(ws: WSClient, ec: ExecutionContext) = this(ws, "")(ec)ĭef repositories(): Future] = §Testing a GitHub clientĪs an example, let’s say you’ve written a GitHub client, and you want to test it.

Play provides some helper utilities for mocking a web service in tests, making this approach to testing a very viable and attractive option. Your tests will show that all the requests it makes are valid HTTP requests, that serialization/deserialization of bodies work, etc, but they will be entirely self contained, not depending on any third party services. This approach is a good compromise between testing against the actual web service and mocking the http client.
#HTTP CLIENT TEST CODE#
Tests against mock web service clients show that the code runs and does certain things, but gives no confidence as to whether anything that the code does actually correlates to valid HTTP requests being made. This approach gives the least confidence in the test code - often this kind of testing amounts to testing no more than that the code does what it does, which is of no value. If the test instance is behind a firewall, it also limits where the tests can be run from. It also means your tests depend on the test instance being running, meaning that test service could cause your build to fail. Many third party web services don’t provide test instances. This is a little better than the previous one, however it still has a number of problems. §Test against a test instance of the web service It may not be possible to set up or ensure the existence of the necessary data that your tests require on that service, and your tests may have undesirable side effects on the service. If it’s a third party web service, there may be rate limiting in place that prevents your tests from running (and running automated tests against a third party service is not considered being a good netizen). This of course gives the highest level of confidence in the client code, however it is usually not practical. Some common approaches include: §Test against the actual web service However testing it also presents some challenges. Since a lot of this code works with strings and weakly typed maps, testing it is very important.
