這很容易用模擬對象完成。我在我的Java項目中使用Mockito,它在Scala中也很實用,尤其是與Scalatest一起使用。
將這個代碼project_dir/build.sbt
:
scalaVersion := "2.10.2"
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "2.0.M8",
"org.mockito" % "mockito-core" % "1.9.5"
)
然後把該代碼project_dir/src/main/test/test.scala
:
import org.scalatest.{FlatSpec,ShouldMatchers}
import org.scalatest.mock.MockitoSugar
package object test {
type Set = Int => Boolean
}
package test {
class Foraller {
def forall(s: Set, p: Int => Boolean): Boolean = ???
}
class Exister(foraller: Foraller) {
def exists(s: Set, p: Int => Boolean): Boolean = ??? // Fails
// def exists(s: Set, p: Int => Boolean): Boolean = foraller.forall(s, p) // Passes
}
class Test extends FlatSpec with ShouldMatchers with MockitoSugar {
"Exister" should "use Foraller in its exists method" in {
val foraller = mock[Foraller]
val exister = new Exister(foraller)
val set: Set = _ == 1
val pred: Int => Boolean = _ > 0
exister.exists(set, pred)
import org.mockito.Mockito._
verify(foraller).forall(set, pred)
}
}
}
然後在project_dir
調用sbt test
命令。你應該看到測試失敗了。切換對Exister
課程中的行的評論,然後重試。
這裏我們爲類提供了模擬對象,它提供了forall
方法,我們在一個提供了exists
方法的類中使用這個對象。 Mockito允許驗證某個模擬對象上的某個方法是否被調用,而這正是在這裏工作的。