PageRenderTime 22ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/documentation/manual/working/javaGuide/main/tests/JavaTestingWebServiceClients.md

https://gitlab.com/KiaraGrouwstra/playframework
Markdown | 88 lines | 61 code | 27 blank | 0 comment | 0 complexity | 388a25cb5f61331230c0157cdb2f47b3 MD5 | raw file
  1. <!--- Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> -->
  2. # Testing web service clients
  3. A lot of code can go into writing a web service client - preparing the request, serializing and deserializing the bodies, setting the correct headers. Since a lot of this code works with strings and weakly typed maps, testing it is very important. However testing it also presents some challenges. Some common approaches include:
  4. ### Test against the actual web service
  5. This of course gives the highest level of confidence in the client code, however it is usually not practical. 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). 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.
  6. ### Test against a test instance of the web service
  7. This is a little better than the previous one, however it still has a number of problems. Many third party web services don't provide test instances. It also means your tests depend on the test instance being running, meaning that test service could cause your build to fail. If the test instance is behind a firewall, it also limits where the tests can be run from.
  8. ### Mock the http client
  9. 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. 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.
  10. ### Mock the web service
  11. This approach is a good compromise between testing against the actual web service and mocking the http client. Your tests will show that all the requests it makes are valid HTTP requests, that serialisation/deserialisation of bodies work, etc, but they will be entirely self contained, not depending on any third party services.
  12. Play provides some helper utilities for mocking a web service in tests, making this approach to testing a very viable and attractive option.
  13. ## Testing a GitHub client
  14. As an example, let's say you've written a GitHub client, and you want to test it. The client is very simple, it just allows you to look up the names of the public repositories:
  15. @[client](code/javaguide/tests/GitHubClient.java)
  16. Note that it takes the GitHub API base URL as a parameter - we'll override this in our tests so that we can point it to our mock server.
  17. To test this, we want an embedded Play server that will implement this endpoint. We can do that by [[Creating an embedded server|JavaEmbeddingPlay]] with the [[Routing DSL|JavaRoutingDsl]]:
  18. @[mock-service](code/javaguide/tests/JavaTestingWebServiceClients.java)
  19. Our server is now running on a random port, that we can access through the `httpPort` method. We could build the base URL to pass to the `GitHubClient` using this, however Play has an even simpler mechanism. The [`WS`](api/java/play/libs/ws/WS.html) class provides a `newClient` method that takes in a port number. When requests are made using the client to relative URLs, eg to `/repositories`, this client will send that request to localhost on the passed in port. This means we can set a base URL on the `GitHubClient` to `""`. It also means if the client returns resources with URL links to other resources that the client then uses to make further requests, we can just ensure those a relative URLs and use them as is.
  20. So now we can create a server, WS client and `GitHubClient` in a `@Before` annotated method, and shut them down in an `@After` annotated method, and then we can test the client in our tests:
  21. @[content](code/javaguide/tests/GitHubClientTest.java)
  22. ### Returning files
  23. In the previous example, we built the json manually for the mocked service. It often will be better to capture an actual response from the service your testing, and return that. To assist with this, Play provides a `sendResource` method that allows easily creating results from files on the classpath.
  24. So after making a request on the actual GitHub API, create a file to store it in the test resources directory. The test resources directory is either `test/resources` if you're using a Play directory layout, or `src/test/resources` if you're using a standard sbt directory layout. In this case, we'll call it `github/repositories.json`, and it will contain the following:
  25. ```json
  26. [
  27. {
  28. "id": 1296269,
  29. "owner": {
  30. "login": "octocat",
  31. "id": 1,
  32. "avatar_url": "https://github.com/images/error/octocat_happy.gif",
  33. "gravatar_id": "",
  34. "url": "https://api.github.com/users/octocat",
  35. "html_url": "https://github.com/octocat",
  36. "followers_url": "https://api.github.com/users/octocat/followers",
  37. "following_url": "https://api.github.com/users/octocat/following{/other_user}",
  38. "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
  39. "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
  40. "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
  41. "organizations_url": "https://api.github.com/users/octocat/orgs",
  42. "repos_url": "https://api.github.com/users/octocat/repos",
  43. "events_url": "https://api.github.com/users/octocat/events{/privacy}",
  44. "received_events_url": "https://api.github.com/users/octocat/received_events",
  45. "type": "User",
  46. "site_admin": false
  47. },
  48. "name": "Hello-World",
  49. "full_name": "octocat/Hello-World",
  50. "description": "This your first repo!",
  51. "private": false,
  52. "fork": false,
  53. "url": "https://api.github.com/repos/octocat/Hello-World",
  54. "html_url": "https://github.com/octocat/Hello-World"
  55. }
  56. ]
  57. ```
  58. You may decide to modify it to suit your testing needs, for example, if your GitHub client used the URLs in the above response to make requests to other endpoints, you might remove the `https://api.github.com` prefix from them so that they too are relative, and will automatically be routed to localhost on the right port by the test client.
  59. Now, modify the router to serve this resource:
  60. @[send-resource](code/javaguide/tests/JavaTestingWebServiceClients.java)
  61. Note that Play will automatically set a content type of `application/json` due to the filename's extension of `.json`.