Search code examples
web-servicesscalatestingplayframework-2.1functional-testing

How can I use Play Framework's FakeApplication to stub out calls to web services via play's WS object?


I'm writing some functional tests in play, however I want to test my stack isolated from other http endpoints.

Is there a mechanism for me to say "Direct WS calls to this set of canned responses" or some other way of stubbing out calls to http endpoints that won't be available for automated tests?

Alternatively, how does fakeApplication config get presented to the rest of the application so I can just set the URL to some localhost server which I'll build myself to provide canned responses


Solution

  • You could create a structural type that mimics the WS signature and use that in your code.

    type WSLike = {
      def url(url: String): WSRequestHolder
    }
    

    Then you can inject your own version of a WSLike class. In combination with a mock library I guess you could do about anything you want.

    As for the second question. You could call it like this:

    val url = Play.current.configuration
      .getString("my.webservice.url")
      .getOrElse(throw new PlayException(
        "Configuration error",
        "Could not find my.webservice.url in settings"))
    
    WS.url(url)
    

    Then in your application.conf add the correct url. You can supply a different one using the FakeApplication.

    FakeApplication(additionalConfiguration = 
      Map("my.webservice.url" -> "http://localhost/service"))