Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unit Test when using ScalaJ-Http?

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.

like image 686
Nelson Avatar asked Nov 08 '22 02:11

Nelson


1 Answers

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.

like image 118
cdmckay Avatar answered Nov 15 '22 10:11

cdmckay