mercredi 11 mars 2020

Trying to mock a HttpEntity in Scala (FlatSpec, Mockito)

  def getResults(response: CloseableHttpResponse): String = {
    getResults(response.getStatusLine.getStatusCode, response.getEntity ())
  }

  def turnHttpEntityToString(response: HttpEntity ): String = {
    val jsonLikeString: String = EntityUtils.toString (response)
    jsonLikeString
  }

  private[coolthing] def getResults(responseHTTPCode:Int, responseEntity: HttpEntity): String = {
    responseHTTPCode match {
      case 200 => turnHttpEntityToString(responseEntity)
      case 400 => ("Bad Request - Please ensure the information you are providing is correct")
      case 500 => ("Internal Server Error")
      case 504 => ("Gateway Timed Out")
      case _ => (s"HTTP Status Code: ${responseHTTPCode}")
    }
  }
}

This is a snippet of the code I am trying to test. The getResults method uses a CloseableHttpResponse which it gets from a method doing a post request to an api.

This test works fine -

 "getResults" should "return a string when the status code is 400" in {
    val r = ApiPostRequest.getScribeResults(400, mockHttpEntity)
    r.mustBe("Bad Request - Please ensure the information you are providing is correct")
  }

And I have done a test similar to this for all the status codes ^ However when it comes to status code 200 and returning the string I want to return, it doesn't seem to like me creating a mock of HttpEntity. I have been messing around trying to figure out if I need to mock another level perhaps?

val mockHttpEntity = mock(classOf[HttpEntity])

 "getScribeResults" should "return the JSON string of Scribe logs and status code of 200" in {
    val r = ApiPostRequest.getScribeResults(200, mockHttpEntity)
    r.mustBe("")
  }

Aucun commentaire:

Enregistrer un commentaire