Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用ScalaMock模拟按名称调用函数?_Scala_Unit Testing_Scalamock - Fatal编程技术网

如何使用ScalaMock模拟按名称调用函数?

如何使用ScalaMock模拟按名称调用函数?,scala,unit-testing,scalamock,Scala,Unit Testing,Scalamock,我希望能够使用ScalaMock模拟我的按名称调用函数,这样它就可以在模拟中运行传递的函数 class MyTest extends Specification with MockFactory { trait myTrait { def myFunction[T](id: Int, name: String)(f: => T): Either[ErrorCode,T] } def futureFunction() = Future { sleep(Rand

我希望能够使用ScalaMock模拟我的按名称调用函数,这样它就可以在模拟中运行传递的函数

class MyTest extends Specification with MockFactory {

  trait myTrait {
    def myFunction[T](id: Int, name: String)(f: => T): Either[ErrorCode,T]
  }

  def futureFunction() = Future {
    sleep(Random.nextInt(500))
    10
  }

  "Mock my trait" should {
    "work" in {
      val test = mock[myTrait]

      (test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall {
        _.productElement(2).asInstanceOf[() => Either[ErrorCode,T]]()
      }
      test.myFunction(25)("test")(futureFunction()) must beEqualTo(10)
    }
  }

}
我尝试以这种方式模拟函数:

(test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall {
    _.productElement(2).asInstanceOf[() => Either[ErrorCode,T]]()
  }
但是当我运行测试时,我得到以下错误:

scala.concurrent.impl.Promise$DefaultPromise@69b28a51 cannot be cast to  Either

如何模拟它,使它在模拟中运行我的futureFunction(),并返回结果。

一位朋友帮助我找到了解决方案。该问题与我对myFunction()的模拟有关。我将一个名函数调用传递给myFunction()(f:=>T),该函数返回T,对其求值后,myFunction()返回或[ErrorCode,T]。所以模拟应该是这样的:

(test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall { test =>
    Right(test.productElement(2).asInstanceOf[() => T]())
}

您可以尝试使用
返回(或者[ErrorCode,T])()
而不是
onCall
。嗯,我需要运行它来解决它。