NKM
NKM

Reputation: 664

Need help creating a dummy WSResponse object (Scala + Play)

I have a code sample as below where I am using WSClient to make API calls. I am using 2.5.x and Scala 2.11.11 (using WSClient provided by Play not stand-alone). In an exception condition I need to return WSResponse object to the caller of this method. From documentation I found Ahc package which provides AhcWSResponse. Any idea how can I create the WSResponse object ? I tried based on a link as below but that does not work.

How to create a WSResponse object from string for Play WSClient

def fetchData (request: WSRequest): Future[WSResponse] = {  
   request.withQueryString("apitoken" -> token).get().flatMap { dataResponse =>
         if (dataResponse.status == 200) {
            Future(Ok(dataResponse.json))
         } else if (dataResponse.status == 400) {
         ...
         }
  }.recover {
     case e: Exception =>
        //need  to return a WSResponse object - how do i create one here 
  }
}

Upvotes: 0

Views: 674

Answers (2)

NKM
NKM

Reputation: 664

There are two ways I can solve this issue:

(1) by creating a dummy WSResponse instance as below:

class DummyWSResponse extends WSResponse {
      def status: Int = 500
      def allHeaders: Map[String, Seq[String]] = ???
      def body: String = ???
      def bodyAsBytes: akka.util.ByteString = ???
      def cookie(name: String): Option[play.api.libs.ws.WSCookie] = ???
      def cookies: Seq[play.api.libs.ws.WSCookie] = ???
      def header(key: String): Option[String] = ???
      def json: play.api.libs.json.JsValue = ???
      def statusText: String = ???
      def underlying[T]: T = ???
      def xml: scala.xml.Elem = ???
   }

(2) [Preferred] Using mockito-scala:

import org.mockito.MockitoSugar._
...
{...}.recover {
   case e: Exception =>
      val mockResponse = mock[WSResponse]
      when(mockResponse.status) thenReturn 500
      mockResponse
}

I used following in my build.sbt to add Mockito dependency:

libraryDependencies += "org.mockito" % "mockito-scala_2.11" % "1.14.4"

Upvotes: 0

Tomer Shetah
Tomer Shetah

Reputation: 8529

Actually you don't need to create it. You have it. dataResponse is of the type you are seeking. Try playing with it and find the data you need. You can try calling:

dataResponse.body

or:

dataResponse.underlying

Upvotes: 0

Related Questions