Skip to content

Instantly share code, notes, and snippets.

@skazhy
Last active August 29, 2015 13:57
Show Gist options
  • Save skazhy/9847529 to your computer and use it in GitHub Desktop.
Save skazhy/9847529 to your computer and use it in GitHub Desktop.
mocking scala-redis RedisClientPool
name := "foo"
version := "1.0"
libraryDependencies ++= Seq(
"net.debasishg" % "redisclient_2.10" % "2.12",
"org.specs2" %% "specs2" % "2.3.10" % "test",
)
import org.specs2.mutable._
import org.specs2.mock._
object Spec extends Specification with Mockito {
"Fetching existing key" should {
"return it's value" in {
val c = mock[com.redis.RedisClientPool]
val wrap = new RedisWrapper(c)
c.withClient(anyFunction1[com.redis.RedisClient, Option[String]]) returns Some("value")
wrap.getOrElse("key", "fallback") mustEqual "value"
}
}
"Fetching absent key" should {
"return fallback value" in {
val c = mock[com.redis.RedisClientPool]
val wrap = new RedisWrapper(c)
c.withClient(anyFunction1[com.redis.RedisClient, Option[String]]) returns None
wrap.getOrElse("key2", "fallback") mustEqual "fallback"
}
}
}
import com.redis._
class RedisWrapper(c: RedisClientPool) {
def set(k: String, v: String) = c.withClient(_.set(k, v))
/** A method to demonstrate that value is returned from Redis & transformed. */
def getOrElse(k: String, f: String) = c.withClient(_.get(k)).getOrElse(f)
}
object Foo {
def main(args: Array[String]) {
val e = new RedisWrapper(new RedisClientPool("localhost", 6379))
e.set("foo", "bar")
printf(e.getOrElse("foo", "404")) // prints foo
printf(e.getOrElse("bar", "404")) // prints 404
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment