为什么我不能告诉mock它应该期望一个类的实例而不显式地给出类型?我的意思是:
val myClass = new MyClass(...)
val traitMock = mock[MyTrait]
(traitMock.mymethod _).expects(myClass).returning(12.3)
不工作,而
val myClass: MyClass = new MyClass(...)
val traitMock = mock[MyTrait]
(traitMock.mymethod _).expects(myClass).returning(12.3)
工作。为什么不能推断类型?
我在build.sbt
中的测试部分是
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "3.0.0" % "test"
exclude("org.scala-lang", "scala-reflect")
exclude("org.scala-lang.modules", "scala-xml")
)
libraryDependencies += "org.scalamock" %% "scalamock-scalatest-support" % "3.3.0" % "test"
因为我被要求MyClass
(这里是SpacePoint
):
trait SpacePoint {
val location: SpaceLocation
}
val sp = new SpacePoint {
override val location: SpaceLocation = new SpaceLocation(DenseVector(1.0, 1.0))
}
所以实际上它为我工作。让我提一下代码中的类型推断:
val myClass = new MyClass(...)
与ScalaMock
无关,但由scala本身保证。下面我将指定带有库版本和类源的工作示例。
测试库:
"org.scalatest" %% "scalatest" % "2.2.4" % "test",
"org.scalamock" %% "scalamock-scalatest-support" % "3.2.2" % "test"
类的源代码:
class MyClass(val something: String)
trait MyTrait {
def mymethod(smth: MyClass): Double
}
测试源代码:
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, WordSpec}
class ScalamockTest extends WordSpec with MockFactory with Matchers {
"ScalaMock" should {
"infers type" in {
val myClass = new MyClass("Hello")
val traitMock = mock[MyTrait]
(traitMock.mymethod _).expects(myClass).returning(12.3)
traitMock.mymethod(myClass) shouldBe 12.3
}
}
}
希望有帮助。一旦您提供更多细节,我们将准备更新答案。