为什么我不能告诉模拟它应该期望一个类的实例而不显式给出类型?这就是我的意思:
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))
}
答案 0 :(得分:1)
实际上对我有用。让我在代码中提到类型推断:
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
}
}
}
希望它有所帮助。一旦您提供更多详细信息,将准备好更新答案。