10

我希望能够模拟getOrElse方法的返回值,以便它返回作为orElseScalaMock 的名称调用参数传递的内容

trait ToBeMocked {
  def getOrElse(arg: Int)(orElse: => String): String
}

由于柯里化,必须使用 ScalaMock。运行这个:

class CallByNameMockSpec extends Specification with MockFactory {

  trait ToBeMocked {
    def getOrElse(arg: Int)(orElse: => String): String
  }

  "Mocking functions with call-by-name arguments" should {
    "work" in {
      val m = mock[ToBeMocked]

      (m.getOrElse (_: Int)(_: String)).expects(101, *).onCall((x, y) => y)

      m.getOrElse(101)("result") must beEqualTo("result")
    }
  }

}

抛出异常:

[error]     ClassCastException:        
test.service.CallByNameMockSpec$$anonfun$1$$anonfun$apply$1$$anonfun$apply$3$$anonfun$apply$4 cannot be cast to java.lang.String (CallByNameMockSpec.scala:16)
4

1 回答 1

5

诀窍是使用方法的Product版本onCall,将第二个参数转换为() => String并调用它:

class CallByNameMockSpec extends Specification with MockFactory {

  trait ToBeMocked {
    def getOrElse(arg: Int)(orElse: => String): String
  }

  "Mocking functions with call-by-name arguments" should {
    "work" in {
      val m = mock[ToBeMocked]

      (m.getOrElse (_: Int)(_: String)).expects(101, *).onCall(_.productElement(1).asInstanceOf[() => String]())

      m.getOrElse(101)("result") must beEqualTo("result")
    }
  }

}
于 2013-08-18T11:17:38.823 回答