在MockFactory之外使用scalamock
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在MockFactory之外使用scalamock相关的知识,希望对你有一定的参考价值。
我想使用黄瓜功能文件为我的项目添加集成测试。我使用这个项目作为一个例子:https://github.com/jecklgamis/cucumber-jvm-scala-example
我遇到的问题是我想要模拟一些对象。 ScalaMock和EasyMock似乎都需要scalatest或类似的东西。
我的build.sbt有这些行:
libraryDependencies ++= Seq(
"io.cucumber" %% "cucumber-scala" % "2.0.1" % Test,
"io.cucumber" % "cucumber-junit" % "2.0.1" % Test,
"org.scalamock" %% "scalamock" % "4.0.0" % Test,
"org.scalatest" %% "scalatest" % "3.0.1" % Test,
etc..
我的stepdef文件有这个:
import com.typesafe.config.{Config, ConfigFactory}
import cucumber.api.scala.{EN, ScalaDsl}
import eu.xeli.jpigpio.JPigpio
class StepDefs extends ScalaDsl with EN {
var config: Config = null
var jpigpio: JPigpio = null
Given("""^an instance of pigpio$""") { () =>
jpigpio = mock[JPigpio]
}
}
mock [JPigpio]调用给出了一个未找到符号的错误。我假设因为这个类没有扩展MockFactory。
如何在MockFactory类之外使用scalamock?
答案
一个快速而肮脏的例子,没有吸引Scalatest,但我相信你可以将其余部分拼凑起来。我真的很想看到这个与黄瓜合作:)
import org.scalamock.MockFactoryBase
import org.scalamock.clazz.Mock
object NoScalaTestExample extends Mock {
trait Cat {
def meow(): Unit
def isHungry: Boolean
}
class MyMockFactoryBase extends MockFactoryBase {
override type ExpectationException = Exception
override protected def newExpectationException(message: String, methodName: Option[Symbol]): Exception =
throw new Exception(s"$message, $methodName")
def verifyAll(): Unit = withExpectations(() => ())
}
implicit var mc: MyMockFactoryBase = _
var cat: Cat = _
def main(args: Array[String]): Unit = {
// given: I have a mock context
mc = new MyMockFactoryBase
// and am mocking a cat
cat = mc.mock[Cat]
// and the cat meows
cat.meow _ expects() once()
// and the cat is always hungry
cat.isHungry _ expects() returning true anyNumberOfTimes()
// then the cat needs feeding
assert(cat.isHungry)
// and the mock verifies
mc.verifyAll()
}
}
这实际上会因为不满意的喵喵期望而抛出(只是为了演示)
Exception in thread "main" java.lang.Exception: Unsatisfied expectation:
Expected:
inAnyOrder {
<mock-1> Cat.meow() once (never called - UNSATISFIED)
<mock-1> Cat.isHungry() any number of times (called once)
}
Actual:
<mock-1> Cat.isHungry(), None
at NoScalaTestExample$MyMockFactoryBase.newExpectationException(NoScalaTestExample.scala:13)
at NoScalaTestExample$MyMockFactoryBase.newExpectationException(NoScalaTestExample.scala:10)
at org.scalamock.context.MockContext$class.reportUnsatisfiedExpectation(MockContext.scala:45)
at NoScalaTestExample$MyMockFactoryBase.reportUnsatisfiedExpectation(NoScalaTestExample.scala:10)
以上是关于在MockFactory之外使用scalamock的主要内容,如果未能解决你的问题,请参考以下文章
在 UITableViewController 之外使用 NSFetchedResultsController