I am looking to use ScalaJ-Http as a http client. Link: https://github.com/scalaj/scalaj-http
How would I mock Http or HttpRequest in a unit test for a class with a line of code like this val response: HttpResponse[String] = Http("http://foo.com/search").param("q","monkeys").asString?
The class will take the url and params from method call arguments. So I cannot inject HttpRequest.
What I did was create a ScalajHttp wrapper class like so:
import scalaj.http.{Http, HttpRequest}
/**
  * This wraps the Scalaj Http object so it can be injected.
  */
class ScalajHttp {
  def url(url: String): HttpRequest = Http(url)
}
Then you can easily inject it into another class:
class Foo(http: ScalajHttp) {
  def doBar() = {
     val response = http.url("http://...").asString
  } 
}
Then for mocking you can use something like Specs2 and create mock of ScalajHttp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With