Sunday, 1 January 2012

Mocking in Scala with ScalaTest and Mockito

It turnes out that mocking with Mockito in Scala is very simple. The only issue is the eq method which I had to map to the.
import org.mockito.Matchers.{eq => the, any}

Dependencies

To use ScalaTest with Mockito you need the following dependencies:
  "org.scalatest" %% "scalatest" % "1.6.1" % "test",
  "org.mockito" % "mockito-core" % "1.9.0" % "test",
Have a look at the example:
package akka.camel
import akka.actor._
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._
import org.mockito.Matchers.{eq => the, any}
class ConsumerScalaTest extends FlatSpec with ShouldMatchers with MockitoSugar{
val system = ActorSystem("test")
"Consumer" should "register itself with Camel during initialization" in{
val mockCamel = mock[ConsumerRegistry]
class TestActor extends Actor with Consumer {
override val camel = mockCamel
from("file://abc")
protected def receive = { case _ => println("foooo..")}
}
system.actorOf(Props(new TestActor()))
verify(mockCamel).registerConsumer(the("file://abc"), any[TestActor])
}
}
view raw gistfile1.scala hosted with ❤ by GitHub

1 comment:

  1. Thanks for the tip on matching eq to the -- in my code, which uses the Specs mockito sugar (http://code.google.com/p/specs/wiki/UsingMockito) eq was actually working, but according to the compiler warning, it shouldn't have been:

    warning: comparing values of types object org.mockito.Matchers and Int using `eq' will always yield false
    [WARNING] something(any, Matchers.eq(1)) returns null

    Your remapping tip above fixed it, but I have no idea why. Any clue?

    ReplyDelete