0

我想使用黄瓜功能文件将集成测试添加到我的项目中。我以这个项目为例进行了这项工作: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?

4

1 回答 1

2

一个快速而肮脏的例子,它没有引入 Scalatest,但我相信你可以将其余部分拼凑在一起。我真的很想看到这个和 Cucumber 一起工作:)

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)
于 2018-01-03T19:03:27.473 回答