Mocking a Post request with apache.http.client.HttpClient in Scala (2.11)

146 Views Asked by At

I'm trying to implement some unit tests for my HttpClient (in Scala 2.11); Here's my client:

import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.{HttpHeaders, HttpResponse}
import org.apache.http.client.HttpClient
import org.apache.http.entity.StringEntity

trait HttpClientFactory extends HttpClientBuilder {
  def create(): HttpClient
}

class HttpClientFactoryImpl extends HttpClientFactory {
  override def create(): HttpClient = HttpClientBuilder.create().build()
}

and then I wrote this method:

  def postRequest[T <: HttpClientFactory](postContent: String, endpoint: String, httpClientFactory: T): HttpResponse = {
    val client = httpClientFactory.create()
    val post = new HttpPost(endpoint)
    post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
    post.setEntity(new StringEntity(postContent))
    client.execute(post)
  }

I wanted to implement a basic unit test using Mockito, something like that:

import org.mockito.Matchers.any
import org.scalatest.{FlatSpec, Matchers}
import org.mockito.Mockito
import org.mockito.Mockito.{mock, when}

class TestClient extends FlatSpec with Matchers {
  "test" should "do something" in {

    val postContent =
      """[
        | {"field1":"1",
        | "field2":"2",
        | "field3": "3"
        |},
        | {"field1":"10",
        | "field2":"20",
        | "field3": "30"
        |}]""".stripMargin

    val endpoint = "www.test.com"
    val post = new HttpPost(endpoint)
    post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
    post.setEntity(new StringEntity(postContent))


    val mockHttpResponse = mock(classOf[HttpResponse])
    val mockStatusLine = mock(classOf[StatusLine])
    when(mockStatusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK)
    when(mockStatusLine.getReasonPhrase()).thenReturn("OK")

    when(mockHttpResponse.getStatusLine()).thenReturn(mockStatusLine)
    val httpClient = mock(classOf[HttpClient])
    when(httpClient.execute(post)).thenReturn(mockHttpResponse)

    val httpClientFactory = mock(classOf[HttpClientFactory])
    when(httpClientFactory.create()).thenReturn(httpClient)

    val result = postRequest[HttpClientFactory](postContent = postContent, endpoint = endpoint, httpClientFactory = httpClientFactory )

    result shouldEqual(mockHttpResponse)
    // or something like result.getStatusLine.getStatusCode shouldEqual(mockStatusLine.getStatusCode)
  }
}

But result is null, and that's my problem!

Any idea of what I am not doing right? Thanks. If you think of a better / simpler way of doing a simple HTTP Post request to a WebApi from a scala job, I take any suggestion.

0

There are 0 best solutions below